@sentry/junior-github 0.301.0 → 0.303.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/events-CrbJHQ0w.js +2466 -0
  2. package/dist/index.d.ts +71 -3
  3. package/dist/index.js +7294 -7881
  4. package/dist/testing.d.ts +51 -1
  5. package/dist/testing.js +1 -6
  6. package/migrations/0012_pull_request_next_action.sql +5 -0
  7. package/migrations/meta/0012_snapshot.json +434 -0
  8. package/migrations/meta/_journal.json +7 -0
  9. package/package.json +11 -13
  10. package/skills/github-code/SKILL.md +1 -1
  11. package/skills/github-code/SPEC.md +2 -2
  12. package/skills/github-code/references/workflow.md +1 -1
  13. package/dist/account-links.d.ts +0 -8
  14. package/dist/annotations.d.ts +0 -33
  15. package/dist/chunk-YUF5P5I7.js +0 -2507
  16. package/dist/clone-command.d.ts +0 -5
  17. package/dist/configured-repository.d.ts +0 -10
  18. package/dist/conversation-title-context.d.ts +0 -20
  19. package/dist/credential-support.d.ts +0 -107
  20. package/dist/db/database.d.ts +0 -5
  21. package/dist/db/schema.d.ts +0 -1403
  22. package/dist/default-branch.d.ts +0 -15
  23. package/dist/egress-policy.d.ts +0 -25
  24. package/dist/events/comment.d.ts +0 -14
  25. package/dist/events/declarations.d.ts +0 -18
  26. package/dist/events/deployment.d.ts +0 -38
  27. package/dist/events/issue.d.ts +0 -42
  28. package/dist/events/pull-request.d.ts +0 -75
  29. package/dist/events/release.d.ts +0 -42
  30. package/dist/events/repository.d.ts +0 -23
  31. package/dist/events/resource-url.d.ts +0 -5
  32. package/dist/events/scope.d.ts +0 -13
  33. package/dist/git-config.d.ts +0 -52
  34. package/dist/github-status.d.ts +0 -16
  35. package/dist/graphql-documents.d.ts +0 -31
  36. package/dist/images.d.ts +0 -8
  37. package/dist/issue-outcomes/store.d.ts +0 -42
  38. package/dist/merge-conflict-checks/heartbeat.d.ts +0 -27
  39. package/dist/merge-conflict-checks/store.d.ts +0 -44
  40. package/dist/merge-conflict-checks/webhooks.d.ts +0 -23
  41. package/dist/object-facts.d.ts +0 -29
  42. package/dist/permissions.d.ts +0 -6
  43. package/dist/plugin.d.ts +0 -45
  44. package/dist/pull-request-outcomes/apply.d.ts +0 -22
  45. package/dist/pull-request-outcomes/commit-composition.d.ts +0 -6
  46. package/dist/pull-request-outcomes/reconcile.d.ts +0 -41
  47. package/dist/pull-request-outcomes/store.d.ts +0 -115
  48. package/dist/pull-request-requesters/draft-reviewers.d.ts +0 -15
  49. package/dist/pull-request-requesters/store.d.ts +0 -41
  50. package/dist/pull-request-review-policy.d.ts +0 -6
  51. package/dist/receive-pack-policy.d.ts +0 -21
  52. package/dist/reply-markdown.d.ts +0 -18
  53. package/dist/sandbox-paths.d.ts +0 -4
  54. package/dist/tool-support/attribution.d.ts +0 -52
  55. package/dist/tool-support/github-api.d.ts +0 -51
  56. package/dist/tool-support/github-text.d.ts +0 -8
  57. package/dist/tool-support/pull-request-description.d.ts +0 -8
  58. package/dist/tools/clone-repository.d.ts +0 -205
  59. package/dist/tools/comment-on-issue.d.ts +0 -205
  60. package/dist/tools/comment-on-pull-request.d.ts +0 -210
  61. package/dist/tools/create-issue.d.ts +0 -218
  62. package/dist/tools/create-pull-request.d.ts +0 -240
  63. package/dist/tools/footer.d.ts +0 -17
  64. package/dist/tools/get-deployment.d.ts +0 -264
  65. package/dist/tools/get-issue.d.ts +0 -248
  66. package/dist/tools/get-pull-request.d.ts +0 -255
  67. package/dist/tools/get-release.d.ts +0 -243
  68. package/dist/tools/get-repository.d.ts +0 -226
  69. package/dist/tools/get-status.d.ts +0 -213
  70. package/dist/tools/react-to-issue.d.ts +0 -205
  71. package/dist/tools/resolve-pull-request-review-thread.d.ts +0 -206
  72. package/dist/tools/stack-pull-request.d.ts +0 -43
  73. package/dist/tools/submit-pull-request-review.d.ts +0 -216
  74. package/dist/tools/update-issue-comment.d.ts +0 -206
  75. package/dist/tools/update-issue.d.ts +0 -249
  76. package/dist/tools/update-pull-request-feedback.d.ts +0 -242
  77. package/dist/tools/update-pull-request.d.ts +0 -255
  78. package/dist/tools.d.ts +0 -13
  79. package/dist/webhooks/check-suite.d.ts +0 -94
  80. package/dist/webhooks/event-targets.d.ts +0 -44
  81. package/dist/webhooks/events.d.ts +0 -23
  82. package/dist/webhooks/fail-open-log.d.ts +0 -10
  83. package/dist/webhooks/handler.d.ts +0 -55
  84. package/dist/webhooks/installation-requests.d.ts +0 -98
  85. package/dist/webhooks/issue-outcome.d.ts +0 -11
  86. package/dist/webhooks/issue-update.d.ts +0 -8
  87. package/dist/webhooks/merge-conflict.d.ts +0 -48
  88. package/dist/webhooks/ownership.d.ts +0 -14
  89. package/dist/webhooks/pull-request-activity.d.ts +0 -11
  90. package/dist/webhooks/pull-request-match-data.d.ts +0 -31
  91. package/dist/webhooks/pull-request-outcome.d.ts +0 -16
  92. package/dist/webhooks/pull-request-people.d.ts +0 -51
  93. package/dist/webhooks/pull-request-preview.d.ts +0 -12
  94. package/dist/webhooks/pull-request-ready-reviewers.d.ts +0 -25
  95. package/dist/webhooks/pull-request-ready.d.ts +0 -31
  96. package/dist/webhooks/pull-request-review-request.d.ts +0 -32
  97. package/dist/workspace-prepare.d.ts +0 -3
@@ -0,0 +1,2466 @@
1
+ import * as z from "zod";
2
+ import { eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
3
+ import { lexer } from "marked";
4
+ import { createPrivateKey, createSign } from "node:crypto";
5
+ // src/permissions.ts
6
+ const LEVELS = /* @__PURE__ */ new Set([
7
+ "read",
8
+ "write",
9
+ "admin"
10
+ ]);
11
+ const WRITE_ONLY_PERMISSIONS = /* @__PURE__ */ new Set(["profile", "workflows"]);
12
+ function isLevel(value) {
13
+ return LEVELS.has(value);
14
+ }
15
+ function normalizeScope(rawScope) {
16
+ return String(rawScope).trim().replace(/-/g, "_");
17
+ }
18
+ /** Validate the configured GitHub App read-token permission declaration. */
19
+ function normalizePermissions(permissions) {
20
+ if (permissions === void 0) return;
21
+ const entries = Object.entries(permissions);
22
+ if (entries.length === 0) throw new Error("githubPlugin appPermissions must contain at least one permission when provided.");
23
+ const request = {};
24
+ for (const [rawScope, rawLevel] of entries) {
25
+ const normalizedScope = normalizeScope(rawScope);
26
+ if (!normalizedScope) throw new Error("githubPlugin appPermissions contains an empty permission name.");
27
+ if (!/^[a-z][a-z0-9_]*$/.test(normalizedScope)) throw new Error(`githubPlugin appPermissions contains invalid permission "${rawScope}".`);
28
+ if (!isLevel(rawLevel)) throw new Error(`githubPlugin appPermissions.${rawScope} must be "read", "write", or "admin".`);
29
+ request[normalizedScope] = rawLevel;
30
+ }
31
+ return request;
32
+ }
33
+ /** Build the read-only installation-token permission body. */
34
+ function readGrantPermissions(permissions) {
35
+ const readOnly = { metadata: "read" };
36
+ for (const [scope, level] of Object.entries(permissions ?? {})) {
37
+ if (!isLevel(level)) throw new Error(`GitHub permission "${scope}" returned invalid level "${String(level)}".`);
38
+ if (!WRITE_ONLY_PERMISSIONS.has(scope)) readOnly[scope] = "read";
39
+ }
40
+ return readOnly;
41
+ }
42
+ // src/events/comment.ts
43
+ /**
44
+ * Filters on the GitHub user who sent the webhook: who wrote a comment or
45
+ * review, or who made an issue update. Resource types that merge these maps
46
+ * keep one description, so it names every case.
47
+ */
48
+ function gitHubSenderMatchFields(events) {
49
+ return eventMatchFieldsSchema.parse({
50
+ senderId: {
51
+ kind: "number",
52
+ description: "immutable numeric GitHub user id of who wrote the comment or review, or made the update; prefer over logins",
53
+ events
54
+ },
55
+ senderLogin: {
56
+ kind: "string",
57
+ description: "GitHub login of who wrote the comment or review, or made the update; logins can be renamed",
58
+ events
59
+ }
60
+ });
61
+ }
62
+ /**
63
+ * Filters on a GitHub comment or review: who wrote it and whether it mentions
64
+ * the App. Issue comments, pull request comments, reviews, and inline review
65
+ * comments set them, so the issue, pull request, and repository resource types
66
+ * share one definition.
67
+ */
68
+ function gitHubCommentMatchFields(events) {
69
+ return eventMatchFieldsSchema.parse({
70
+ mentionsBot: {
71
+ kind: "boolean",
72
+ description: "true when the comment or review mentions this GitHub App",
73
+ events
74
+ },
75
+ ...gitHubSenderMatchFields(events)
76
+ });
77
+ }
78
+ // src/events/scope.ts
79
+ /**
80
+ * `repo` in event data: lowercase `owner/repo`. GitHub ignores case in
81
+ * repository names, so tools accept this form.
82
+ */
83
+ const gitHubRepoDataSchema = z.string().min(1).toLowerCase();
84
+ /** `commitSha` in event data: the full lowercase commit SHA. */
85
+ const gitHubCommitShaDataSchema = z.string().regex(/^[0-9a-f]{40}$/i).toLowerCase();
86
+ /** Filter on the repository of an event. */
87
+ function gitHubRepoMatchFields(events) {
88
+ return eventMatchFieldsSchema.parse({ repo: {
89
+ kind: "string",
90
+ case: "lower",
91
+ description: "lowercase repository as owner/repo, such as getsentry/junior",
92
+ events
93
+ } });
94
+ }
95
+ /** Filter on the commit of an event. */
96
+ function gitHubCommitMatchFields(events) {
97
+ return eventMatchFieldsSchema.parse({ commitSha: {
98
+ kind: "string",
99
+ case: "lower",
100
+ description: "full lowercase Git commit SHA",
101
+ events
102
+ } });
103
+ }
104
+ // src/events/issue.ts
105
+ const GITHUB_ISSUE_EVENTS = [
106
+ "issue.comment.created",
107
+ "issue.opened",
108
+ "issue.closed",
109
+ "issue.reopened",
110
+ "issue.updated"
111
+ ];
112
+ const GITHUB_ISSUE_SUGGESTED_EVENTS = [
113
+ "issue.comment.created",
114
+ "issue.closed",
115
+ "issue.reopened",
116
+ "issue.updated"
117
+ ];
118
+ /**
119
+ * The `issues` webhook actions that `issue.updated` publishes. The webhook
120
+ * schema and the `change` match field both use this list.
121
+ */
122
+ const GITHUB_ISSUE_UPDATE_CHANGES = [
123
+ "edited",
124
+ "labeled",
125
+ "unlabeled",
126
+ "assigned",
127
+ "unassigned",
128
+ "milestoned",
129
+ "demilestoned"
130
+ ];
131
+ /**
132
+ * Exact values GitHub sets on issue event data. Every issue event sets the
133
+ * repository and issue number. Comments and updates set who acted. Only
134
+ * updates set `change` and `label`, so an automation can run on one label
135
+ * that one person adds without the model deciding from untrusted text.
136
+ */
137
+ const GITHUB_ISSUE_MATCH_FIELDS = mergeEventMatchFields(gitHubCommentMatchFields(["issue.comment.created"]), gitHubSenderMatchFields(["issue.updated"]), eventMatchFieldsSchema.parse({
138
+ ...gitHubRepoMatchFields(GITHUB_ISSUE_EVENTS),
139
+ issue: {
140
+ kind: "number",
141
+ description: "issue number, such as 12",
142
+ events: GITHUB_ISSUE_EVENTS
143
+ },
144
+ change: {
145
+ kind: "string",
146
+ enum: [...GITHUB_ISSUE_UPDATE_CHANGES],
147
+ description: "what the issue update changed, such as labeled",
148
+ events: ["issue.updated"]
149
+ },
150
+ label: {
151
+ kind: "string",
152
+ case: "lower",
153
+ description: "lowercase name of the label that was added or removed, set only when change is labeled or unlabeled",
154
+ events: ["issue.updated"]
155
+ }
156
+ }));
157
+ /** The identifier shape that `gitHubIssueResource` builds. */
158
+ const GITHUB_ISSUE_IDENTIFIER = {
159
+ format: "owner/repo#number",
160
+ pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
161
+ };
162
+ /** Build the stable issue identity shared by tools and webhooks. */
163
+ function gitHubIssueResource(input) {
164
+ return {
165
+ label: `GitHub issue ${input.repo}#${input.number}`,
166
+ namespace: "github",
167
+ identifier: `${input.repo.toLowerCase()}#${input.number}`
168
+ };
169
+ }
170
+ /**
171
+ * Describe an issue as a resource that a conversation can watch.
172
+ * Return undefined when the host cannot create Watches.
173
+ */
174
+ function gitHubIssueSubscribable(input) {
175
+ if (!input.canSubscribe) return void 0;
176
+ return {
177
+ ...gitHubIssueResource(input),
178
+ match: {
179
+ repo: gitHubRepoDataSchema.parse(input.repo),
180
+ issue: input.number
181
+ },
182
+ suggested_events: GITHUB_ISSUE_SUGGESTED_EVENTS,
183
+ supported_events: GITHUB_ISSUE_EVENTS,
184
+ type: "issue"
185
+ };
186
+ }
187
+ // src/events/deployment.ts
188
+ const GITHUB_DEPLOYMENT_EVENTS = [
189
+ "deployment.created",
190
+ "deployment.queued",
191
+ "deployment.pending",
192
+ "deployment.in_progress",
193
+ "deployment.succeeded",
194
+ "deployment.failed",
195
+ "deployment.error"
196
+ ];
197
+ const GITHUB_DEPLOYMENT_SUGGESTED_EVENTS = [
198
+ "deployment.succeeded",
199
+ "deployment.failed",
200
+ "deployment.error"
201
+ ];
202
+ /**
203
+ * Trusted deployment values that watches and event automations can match.
204
+ * Every deployment event sets them; the repository resource type also has
205
+ * events that do not.
206
+ */
207
+ const GITHUB_DEPLOYMENT_MATCH_FIELDS = eventMatchFieldsSchema.parse({
208
+ ...gitHubRepoMatchFields(GITHUB_DEPLOYMENT_EVENTS),
209
+ ...gitHubCommitMatchFields(GITHUB_DEPLOYMENT_EVENTS),
210
+ deploymentId: {
211
+ kind: "number",
212
+ description: "numeric GitHub deployment id, such as 3001",
213
+ events: [...GITHUB_DEPLOYMENT_EVENTS]
214
+ },
215
+ environment: {
216
+ kind: "string",
217
+ case: "lower",
218
+ description: "lowercase deployment environment name, such as production",
219
+ events: [...GITHUB_DEPLOYMENT_EVENTS]
220
+ },
221
+ workflowId: {
222
+ kind: "number",
223
+ description: "numeric GitHub Actions workflow id when a workflow created the deployment",
224
+ events: [...GITHUB_DEPLOYMENT_EVENTS]
225
+ },
226
+ workflowPath: {
227
+ kind: "string",
228
+ description: "GitHub Actions workflow file, such as .github/workflows/deploy.yml, when a workflow created the deployment",
229
+ events: [...GITHUB_DEPLOYMENT_EVENTS]
230
+ }
231
+ });
232
+ /** The identifier shape that `gitHubDeploymentSourceResource` builds. */
233
+ const GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER = {
234
+ format: "deployment-source:owner/repo[:environment]:<full-commit-sha>",
235
+ pattern: String.raw`^deployment-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?:[0-9a-f]+$`
236
+ };
237
+ /** Build the stable deployment-source identity shared by tools and webhooks. */
238
+ function gitHubDeploymentSourceResource(input) {
239
+ const commitSha = input.commitSha.toLowerCase();
240
+ const environment = input.environment?.trim();
241
+ const repo = input.repo.toLowerCase();
242
+ return {
243
+ label: `GitHub deployment for ${repo} at ${commitSha.slice(0, 12)}`,
244
+ namespace: "github",
245
+ identifier: environment ? `deployment-source:${repo}:${encodeURIComponent(environment.toLowerCase())}:${commitSha}` : `deployment-source:${repo}:${commitSha}`
246
+ };
247
+ }
248
+ /**
249
+ * Describe a deployment source that a conversation can watch.
250
+ * Return undefined when the host cannot create Watches.
251
+ */
252
+ function gitHubDeploymentSourceSubscribable(input) {
253
+ if (!input.canSubscribe) return void 0;
254
+ const environment = input.environment?.trim().toLowerCase();
255
+ return {
256
+ ...gitHubDeploymentSourceResource(input),
257
+ match: {
258
+ repo: gitHubRepoDataSchema.parse(input.repo),
259
+ commit_sha: gitHubCommitShaDataSchema.parse(input.commitSha),
260
+ ...environment ? { environment } : void 0
261
+ },
262
+ suggested_events: GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
263
+ supported_events: [...GITHUB_DEPLOYMENT_EVENTS],
264
+ type: "deployment_source"
265
+ };
266
+ }
267
+ // src/events/pull-request.ts
268
+ const GITHUB_PULL_REQUEST_EVENTS = [
269
+ "pull_request.checks.failed",
270
+ "pull_request.checks.passed",
271
+ "pull_request.checks.recovered",
272
+ "pull_request.comment.created",
273
+ "pull_request.opened",
274
+ "pull_request.ready_for_review",
275
+ "pull_request.review.approved",
276
+ "pull_request.review.changes_requested",
277
+ "pull_request.review.commented",
278
+ "pull_request.review_comment.created",
279
+ "pull_request.merged",
280
+ "pull_request.closed_unmerged",
281
+ "pull_request.merge_conflict"
282
+ ];
283
+ /**
284
+ * A stack merges only with a linear history, so a stacked pull request is
285
+ * rebased, never merged with its base. GitHub rebases the next pull request
286
+ * after a merge, but it stops at a conflict and sends no event for it.
287
+ */
288
+ const STACK_CHECK = "Check if the pull request is in a stack: `gh api 'repos/OWNER/REPO/stacks?pull_request=NUMBER'`.";
289
+ const STACK_CONFLICT_STEPS = "run `gh stack rebase`, resolve each conflict so that both changes stay intact, stage the files, and run `gh stack rebase --continue`. Run the checks again, run `gh stack push`, and confirm that each open pull request in the stack can merge. Report the files that had conflicts.";
290
+ /**
291
+ * Every comment on a pull request gets the same feedback status: a
292
+ * conversation comment, an inline review comment, and a review body. A review
293
+ * sets comment_id only when it has a body.
294
+ */
295
+ const PULL_REQUEST_FEEDBACK = "When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status \"addressed\" or \"declined\".";
296
+ const GITHUB_PULL_REQUEST_EVENT_GUIDANCE = {
297
+ "pull_request.checks.failed": "Fix only failures that the pull request causes. Do not skip, disable, or weaken a check to make it pass.",
298
+ "pull_request.review.approved": `When the approval includes actionable feedback, address it like any other review feedback. ${PULL_REQUEST_FEEDBACK}`,
299
+ "pull_request.review.changes_requested": PULL_REQUEST_FEEDBACK,
300
+ "pull_request.review.commented": PULL_REQUEST_FEEDBACK,
301
+ "pull_request.comment.created": PULL_REQUEST_FEEDBACK,
302
+ "pull_request.review_comment.created": `${PULL_REQUEST_FEEDBACK} Then resolve the thread with github_resolvePullRequestReviewThread.`,
303
+ "pull_request.merge_conflict": `${STACK_CHECK} If it is, run \`gh stack checkout NUMBER\`, then ${STACK_CONFLICT_STEPS} If it is not, fetch base_branch from Verified details and merge it into the pull request branch. Do not rebase. Resolve each conflict so that both the pull request change and the base branch change stay intact. Run the checks again, push, and confirm that the pull request can merge. Report the files that had conflicts.`
304
+ };
305
+ /** Combine provider defaults with app guidance for pull request events. */
306
+ function gitHubPullRequestEventGuidance(guidance) {
307
+ const merged = { ...GITHUB_PULL_REQUEST_EVENT_GUIDANCE };
308
+ for (const eventType of GITHUB_PULL_REQUEST_EVENTS) {
309
+ const extra = guidance?.[eventType]?.trim();
310
+ if (!extra) continue;
311
+ const base = merged[eventType];
312
+ merged[eventType] = base ? `${base} ${extra}` : extra;
313
+ }
314
+ return merged;
315
+ }
316
+ /**
317
+ * Junior maintains the pull requests it creates. The pull request is its own
318
+ * work, so it answers and fixes review feedback without asking first.
319
+ */
320
+ const DEFAULT_PULL_REQUEST_SUBSCRIPTION = {
321
+ events: [
322
+ "pull_request.checks.failed",
323
+ "pull_request.closed_unmerged",
324
+ "pull_request.comment.created",
325
+ "pull_request.review.changes_requested",
326
+ "pull_request.review.commented",
327
+ "pull_request.review_comment.created"
328
+ ],
329
+ intent: "Maintain pull requests Junior creates. For actionable review feedback or failed checks, inspect the evidence, make scoped fixes, verify them, and push, without asking first. Reply on GitHub to review comments and questions, in the thread where they were asked. Report completed work or blockers in the originating thread. Report when the pull request closes unmerged. When a reviewer submits a review, notify the person who asked for the pull request by mentioning them, with the reviewer, the review outcome, and the pull request link. Stay silent on other events that are not feedback."
330
+ };
331
+ /** Resolve the Watch to create after Junior creates a pull request, if any. */
332
+ function gitHubPullRequestSubscription(config) {
333
+ if (config === false) return void 0;
334
+ return config ?? DEFAULT_PULL_REQUEST_SUBSCRIPTION;
335
+ }
336
+ /**
337
+ * Watch guidance for outcomes that the people involved need to hear about.
338
+ * The Watch made after Junior creates a pull request always receives these
339
+ * events. The webhook adds the people involved in the pull request to them.
340
+ * A merge does not ask the agent to check for a stack: GitHub rebases the
341
+ * next pull request in a stack itself, and most merges are not stacked.
342
+ */
343
+ const GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE = {
344
+ "pull_request.review.approved": `Mention each person in People involved, or the person who asked for the pull request if that line is missing. Say who approved it and link it. Do not merge it unless asked. Do not guess whether it can merge. Before you say anything about that, call github_getPullRequest and read its \`checks\`. If \`checks.required\` is \`not_reported\`, the required checks may not have started on the latest commit yet. It does not mean that none are required. If \`checks.auto_merge\` is true and only required checks remain, say only that it merges when they pass. If \`checks.merge_state\` shows that GitHub blocks it for another reason, run \`gh api repos/OWNER/REPO/rules/branches/BASE\` and name the rule that blocks it. Do not say that you did not merge it.`,
345
+ "pull_request.merged": "Mention each person in People involved, or the person who asked for the pull request if that line is missing. Say that it merged and link it."
346
+ };
347
+ /**
348
+ * Junior finishes its own drafts. Passing checks start no other step, so the
349
+ * Watch of a draft also gets them. Marking the pull request ready sends the
350
+ * review request. GitHub also asks the code owners then, so a draft with code
351
+ * owners waits for the person who asked for it, unless they said otherwise.
352
+ * A repository's AGENTS.md can also ask that drafts wait for a person.
353
+ * Each passing suite wakes the Watch, so a suite that leaves the required
354
+ * checks unfinished must stay silent, or every suite posts.
355
+ */
356
+ const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open review item that waits on the person who asked for it: mark it ready with github_updatePullRequest and draft false, and report that in the originating thread, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. When it is `failing`, fix the failing checks like a failed check. When it is `pending` or `not_reported`, stay silent: a later passing suite wakes you again. `not_reported` means the required checks may not have started on the latest commit yet, not that none are required.";
357
+ /**
358
+ * Build the Watch created after Junior creates a pull request. Only a draft
359
+ * Watch gets passing checks, so a ready pull request is not woken by each
360
+ * passing check suite.
361
+ */
362
+ function gitHubPullRequestCreateWatch(config, pullRequest) {
363
+ const outcomeEvents = Object.keys(GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE);
364
+ return {
365
+ events: [.../* @__PURE__ */ new Set([
366
+ ...config.events,
367
+ "pull_request.merge_conflict",
368
+ ...outcomeEvents,
369
+ ...pullRequest.draft ? ["pull_request.checks.recovered"] : []
370
+ ])],
371
+ guidance: pullRequest.draft ? {
372
+ ...GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE,
373
+ "pull_request.checks.recovered": DRAFT_CHECKS_RECOVERED_GUIDANCE
374
+ } : GITHUB_PULL_REQUEST_OUTCOME_GUIDANCE,
375
+ intent: config.intent
376
+ };
377
+ }
378
+ const GITHUB_PULL_REQUEST_SUGGESTED_EVENTS = [
379
+ "pull_request.checks.failed",
380
+ "pull_request.comment.created",
381
+ "pull_request.ready_for_review",
382
+ "pull_request.review.changes_requested",
383
+ "pull_request.review.commented",
384
+ "pull_request.review_comment.created",
385
+ "pull_request.merged",
386
+ "pull_request.closed_unmerged",
387
+ "pull_request.merge_conflict"
388
+ ];
389
+ /**
390
+ * Pull request events that a GitHub webhook payload describes. GitHub sends
391
+ * no webhook when a pull request gets a conflict, so the webhook reads the
392
+ * pull request for `pull_request.merge_conflict` instead.
393
+ */
394
+ const GITHUB_PULL_REQUEST_PAYLOAD_EVENTS = GITHUB_PULL_REQUEST_EVENTS.filter((eventType) => eventType !== "pull_request.merge_conflict");
395
+ /** Pull request events that a comment or review starts. */
396
+ const GITHUB_PULL_REQUEST_COMMENT_EVENTS = [
397
+ "pull_request.comment.created",
398
+ "pull_request.review.approved",
399
+ "pull_request.review.changes_requested",
400
+ "pull_request.review.commented",
401
+ "pull_request.review_comment.created"
402
+ ];
403
+ /** Pull request events that a check suite result starts. */
404
+ const GITHUB_PULL_REQUEST_CHECK_EVENTS = [
405
+ "pull_request.checks.failed",
406
+ "pull_request.checks.passed",
407
+ "pull_request.checks.recovered"
408
+ ];
409
+ /**
410
+ * Exact values GitHub may set on pull request event data. Missing keys do not
411
+ * match. The opener and author values load in
412
+ * `webhooks/pull-request-match-data.ts` for every payload pull request event.
413
+ * The pull request comment webhook has no head branch. A check suite result
414
+ * that GitHub links to no pull request has no `pullRequest`. The webhook
415
+ * checks for a Watch or event automation before it reads a pull request for
416
+ * a conflict, so `pull_request.merge_conflict` matches only `repo` and
417
+ * `pullRequest`.
418
+ */
419
+ const GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema.parse({
420
+ ...gitHubCommentMatchFields(GITHUB_PULL_REQUEST_COMMENT_EVENTS),
421
+ ...gitHubRepoMatchFields(GITHUB_PULL_REQUEST_EVENTS),
422
+ ...gitHubCommitMatchFields(GITHUB_PULL_REQUEST_CHECK_EVENTS),
423
+ pullRequest: {
424
+ kind: "number",
425
+ description: "pull request number, such as 946",
426
+ events: [...GITHUB_PULL_REQUEST_EVENTS]
427
+ },
428
+ authors: {
429
+ kind: "string",
430
+ list: true,
431
+ description: "GitHub logins of the commit authors and Co-authored-by people, including bots such as this GitHub App",
432
+ events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
433
+ },
434
+ headBranch: {
435
+ kind: "string",
436
+ description: "head branch name from the webhook",
437
+ events: GITHUB_PULL_REQUEST_PAYLOAD_EVENTS.filter((eventType) => eventType !== "pull_request.comment.created")
438
+ },
439
+ isDraft: {
440
+ kind: "boolean",
441
+ description: "true when the pull request is a draft",
442
+ events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
443
+ },
444
+ openerEmail: {
445
+ kind: "string",
446
+ description: "opener email when GitHub sends it; missing on pull requests that this GitHub App opened",
447
+ events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
448
+ },
449
+ openerUsername: {
450
+ kind: "string",
451
+ description: "login of who opened the pull request; on pull requests that this GitHub App opened, the person who asked for it, missing until that person is saved",
452
+ events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
453
+ },
454
+ openerRole: {
455
+ kind: "string",
456
+ description: "opener's repository role: admin, maintain, write, triage, read, none (no access, such as most bots), or a custom role name",
457
+ events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
458
+ }
459
+ });
460
+ /** The identifier shape that `gitHubPullRequestResource` builds. */
461
+ const GITHUB_PULL_REQUEST_IDENTIFIER = {
462
+ format: "owner/repo#number",
463
+ pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
464
+ };
465
+ /** Build the stable pull request identity shared by tools and webhooks. */
466
+ function gitHubPullRequestResource(input) {
467
+ return {
468
+ label: `GitHub PR ${input.repo}#${input.number}`,
469
+ namespace: "github",
470
+ identifier: `${input.repo.toLowerCase()}#${input.number}`
471
+ };
472
+ }
473
+ /**
474
+ * Describe a pull request as a resource that a conversation can watch.
475
+ * Return undefined when the host cannot create Watches.
476
+ */
477
+ function gitHubPullRequestSubscribable(input) {
478
+ if (!input.canSubscribe) return void 0;
479
+ const omitted = new Set(input.omitSuggestedEvents ?? []);
480
+ const suggestedEvents = GITHUB_PULL_REQUEST_SUGGESTED_EVENTS.filter((eventType) => !omitted.has(eventType));
481
+ return {
482
+ ...gitHubPullRequestResource(input),
483
+ match: {
484
+ repo: gitHubRepoDataSchema.parse(input.repo),
485
+ pull_request: input.number
486
+ },
487
+ ...suggestedEvents.length > 0 ? { suggested_events: [...suggestedEvents] } : void 0,
488
+ supported_events: [...GITHUB_PULL_REQUEST_EVENTS],
489
+ type: "pull_request"
490
+ };
491
+ }
492
+ // src/events/release.ts
493
+ const GITHUB_RELEASE_EVENTS = ["release.published"];
494
+ /**
495
+ * `tag` in event data: the trimmed tag with ASCII letters in lowercase. The
496
+ * release-source identifier has the URI-encoded tag, and the plugin
497
+ * lowercases identifiers. Encoding turns other characters into `%XX`
498
+ * escapes, so only ASCII letters change case there. This form is the same
499
+ * text, so `release/1.0` is not `release%2f1.0`, and `Ü` stays `Ü`. To turn
500
+ * an identifier into a `tag` filter, decode its tag part.
501
+ */
502
+ const gitHubReleaseTagDataSchema = z.string().trim().min(1).transform((tag) => tag.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()));
503
+ /** Exact values that every release event sets. */
504
+ const GITHUB_RELEASE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
505
+ ...gitHubRepoMatchFields(GITHUB_RELEASE_EVENTS),
506
+ tag: {
507
+ kind: "string",
508
+ description: "release tag with ASCII letters in lowercase, such as v1.2.0 or release/1.0",
509
+ events: [...GITHUB_RELEASE_EVENTS]
510
+ }
511
+ });
512
+ const GITHUB_RELEASE_SUGGESTED_EVENTS = ["release.published"];
513
+ /** The identifier shape that `gitHubReleaseSourceResource` builds. */
514
+ const GITHUB_RELEASE_SOURCE_IDENTIFIER = {
515
+ format: "release-source:owner/repo[:tag]",
516
+ pattern: String.raw`^release-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?$`
517
+ };
518
+ /** Build the stable release-source identity shared by tools and webhooks. */
519
+ function gitHubReleaseSourceResource(input) {
520
+ const repo = input.repo.toLowerCase();
521
+ const tag = input.tag?.trim();
522
+ return {
523
+ label: `GitHub release for ${repo}`,
524
+ namespace: "github",
525
+ identifier: tag ? `release-source:${repo}:${encodeURIComponent(tag)}` : `release-source:${repo}`
526
+ };
527
+ }
528
+ /**
529
+ * Describe a release source that a conversation can watch.
530
+ * Return undefined when the host cannot create Watches.
531
+ */
532
+ function gitHubReleaseSourceSubscribable(input) {
533
+ if (!input.canSubscribe) return void 0;
534
+ const tag = input.tag?.trim();
535
+ return {
536
+ ...gitHubReleaseSourceResource(input),
537
+ match: {
538
+ repo: gitHubRepoDataSchema.parse(input.repo),
539
+ ...tag ? { tag: gitHubReleaseTagDataSchema.parse(tag) } : void 0
540
+ },
541
+ suggested_events: GITHUB_RELEASE_SUGGESTED_EVENTS,
542
+ supported_events: [...GITHUB_RELEASE_EVENTS],
543
+ type: "release_source"
544
+ };
545
+ }
546
+ // src/events/repository.ts
547
+ /** The identifier shape that `gitHubRepositoryResource` builds. */
548
+ const GITHUB_REPOSITORY_IDENTIFIER = {
549
+ format: "owner/repo",
550
+ pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+$`
551
+ };
552
+ /** Build the stable repository identity shared by tools and webhooks. */
553
+ function gitHubRepositoryResource(input) {
554
+ return {
555
+ label: `GitHub repository ${input.repo}`,
556
+ namespace: "github",
557
+ identifier: input.repo.toLowerCase()
558
+ };
559
+ }
560
+ /** Events that a repository Watch gets: deployments, issues, and pull requests. */
561
+ const GITHUB_REPOSITORY_EVENTS = [
562
+ ...GITHUB_DEPLOYMENT_EVENTS,
563
+ ...GITHUB_ISSUE_EVENTS,
564
+ ...GITHUB_PULL_REQUEST_EVENTS
565
+ ];
566
+ /** Repository events to suggest when a conversation starts a Watch. */
567
+ const GITHUB_REPOSITORY_SUGGESTED_EVENTS = [
568
+ "issue.opened",
569
+ "pull_request.opened",
570
+ ...GITHUB_ISSUE_SUGGESTED_EVENTS.filter((eventType) => eventType !== "issue.updated"),
571
+ ...GITHUB_PULL_REQUEST_SUGGESTED_EVENTS
572
+ ];
573
+ /**
574
+ * Describe a repository as a resource that a conversation can watch.
575
+ * Return undefined when the host cannot create Watches.
576
+ */
577
+ function gitHubRepositorySubscribable(input) {
578
+ if (!input.canSubscribe) return void 0;
579
+ return {
580
+ ...gitHubRepositoryResource(input),
581
+ match: { repo: gitHubRepoDataSchema.parse(input.repo) },
582
+ suggested_events: [...GITHUB_REPOSITORY_SUGGESTED_EVENTS],
583
+ supported_events: [...GITHUB_REPOSITORY_EVENTS],
584
+ type: "repository"
585
+ };
586
+ }
587
+ // src/webhooks/ownership.ts
588
+ const GITHUB_BOT_NOREPLY_EMAIL = /^(?<userId>[1-9]\d*)\+(?<login>[^@]+\[bot\])@users\.noreply\.github\.com$/i;
589
+ /** Parse the bot identity encoded in GitHub's standard noreply address. */
590
+ function parseGitHubBotIdentity(value) {
591
+ const match = GITHUB_BOT_NOREPLY_EMAIL.exec(value?.trim() ?? "");
592
+ const login = match?.groups?.["login"];
593
+ const userId = match?.groups?.["userId"];
594
+ if (!login || !userId) return void 0;
595
+ return {
596
+ login,
597
+ userId: Number(userId)
598
+ };
599
+ }
600
+ /** Derive the provider login encoded in a standard GitHub noreply address. */
601
+ function botLoginFromEmail(value) {
602
+ return parseGitHubBotIdentity(value)?.login;
603
+ }
604
+ /** Check whether a GitHub login is the bot encoded in the configured bot email. */
605
+ function isBotLogin(login, botEmail) {
606
+ const botLogin = botLoginFromEmail(botEmail)?.toLowerCase();
607
+ return Boolean(botLogin && login?.trim().toLowerCase() === botLogin);
608
+ }
609
+ /** Derive the GitHub user id encoded in a standard GitHub noreply address. */
610
+ function botUserIdFromEmail(value) {
611
+ return parseGitHubBotIdentity(value)?.userId;
612
+ }
613
+ const SKIPPED_TOKEN_TYPES = /* @__PURE__ */ new Set([
614
+ "blockquote",
615
+ "code",
616
+ "codespan",
617
+ "html"
618
+ ]);
619
+ /**
620
+ * Collect the text of Markdown tokens outside quotes, code, and HTML. Join
621
+ * inline tokens with no separator, so `me@bot` stays one word.
622
+ */
623
+ function ownTokenText(tokens, separator = "") {
624
+ return tokens.map((token) => {
625
+ if (SKIPPED_TOKEN_TYPES.has(token.type)) return " ";
626
+ if (token.type === "list") return token.items.map((item) => ownTokenText(item.tokens, "\n")).join("\n");
627
+ if (token.type === "table") {
628
+ const table = token;
629
+ return [table.header, ...table.rows].flat().map((cell) => ownTokenText(cell.tokens)).join(" ");
630
+ }
631
+ if ("tokens" in token && token.tokens) return ownTokenText(token.tokens);
632
+ return "text" in token ? token.text : token.raw;
633
+ }).join(separator);
634
+ }
635
+ /**
636
+ * Keep the author's own text. A GitHub-flavored Markdown parser finds the
637
+ * quotes and code, the same as GitHub when it renders the comment.
638
+ */
639
+ function ownCommentText(text) {
640
+ return ownTokenText(lexer(text, { gfm: true }), "\n");
641
+ }
642
+ /**
643
+ * Check whether the author's own text mentions the bot encoded in the
644
+ * configured bot email. GitHub sends mentions only as comment text, with no
645
+ * structured field, so this reads the App slug: the bot login without `[bot]`.
646
+ * This shows only that the comment addresses the bot. It does not grant trust;
647
+ * match the commenter's `senderId` for that.
648
+ */
649
+ function mentionsBotLogin(text, botEmail) {
650
+ const slug = botLoginFromEmail(botEmail)?.replace(/\[bot\]$/i, "");
651
+ if (!slug) return false;
652
+ const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
653
+ return new RegExp(`(?:^|[^\\w-])@${escaped}(?![\\w-])`, "i").test(ownCommentText(text));
654
+ }
655
+ // src/credential-support.ts
656
+ /**
657
+ * GitHub credential issuance and provider request support.
658
+ *
659
+ * This module owns OAuth refresh, installation tokens, credential leases, and
660
+ * installation and user credential parsing.
661
+ */
662
+ const GITHUB_APP_ID_ENV = "GITHUB_APP_ID";
663
+ const GITHUB_APP_PRIVATE_KEY_ENV = "GITHUB_APP_PRIVATE_KEY";
664
+ const GITHUB_INSTALLATION_ID_ENV = "GITHUB_INSTALLATION_ID";
665
+ const GITHUB_AUTH_TOKEN_ENV = "GITHUB_TOKEN";
666
+ const GITHUB_AUTH_TOKEN_PLACEHOLDER = "ghp_host_managed_credential";
667
+ const MAX_LEASE_MS = 36e5;
668
+ const REFRESH_BUFFER_MS = 3e5;
669
+ const USER_REFRESH_TIMEOUT_MS = 2e4;
670
+ const GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES = 65536;
671
+ const HTTP_READ_METHODS = /* @__PURE__ */ new Set([
672
+ "GET",
673
+ "HEAD",
674
+ "OPTIONS"
675
+ ]);
676
+ const USER_TOKEN_GRANTS = /* @__PURE__ */ new Set(["user-read", "user-write"]);
677
+ const CREATE_TOOL_ROUTING_GUIDANCE = "This is a tool-routing denial, not a GitHub permission failure. Do not ask the user for GitHub permissions; retry with the required tool.";
678
+ const USER_WRITE_REQUIREMENTS = ["requesting GitHub user permission to perform this operation"];
679
+ const GITHUB_CREDENTIAL_DOMAINS = ["api.github.com", "github.com"];
680
+ const GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS = [...GITHUB_CREDENTIAL_DOMAINS, "uploads.github.com"];
681
+ var GitHubUserRefreshRejectedError = class extends Error {
682
+ constructor(message) {
683
+ super(message);
684
+ this.name = "GitHubUserRefreshRejectedError";
685
+ }
686
+ };
687
+ /** A GitHub API response with an error status. */
688
+ var GitHubRequestError = class extends Error {
689
+ status;
690
+ constructor(message, status) {
691
+ super(message);
692
+ this.name = "GitHubRequestError";
693
+ this.status = status;
694
+ }
695
+ };
696
+ var GitHubPluginSetupError = class extends Error {
697
+ constructor(message) {
698
+ super(message);
699
+ this.name = "GitHubPluginSetupError";
700
+ }
701
+ };
702
+ /** Return whether a provider value is a JSON object. */
703
+ function isRecord(value) {
704
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
705
+ }
706
+ /** Read a non-empty GitHub plugin environment value. */
707
+ function readEnv(name) {
708
+ const value = process.env[name];
709
+ if (typeof value !== "string") return;
710
+ const trimmed = value.trim();
711
+ return trimmed ? trimmed : void 0;
712
+ }
713
+ /** Read a required GitHub plugin environment value. */
714
+ function requireEnv(name) {
715
+ const value = readEnv(name);
716
+ if (!value) throw new GitHubPluginSetupError(`Missing ${name}`);
717
+ return value;
718
+ }
719
+ /** Normalize configured GitHub OAuth scopes. */
720
+ function normalizeScopeList(scopes) {
721
+ return [...new Set((scopes ?? []).flatMap((scope) => String(scope).split(/\s+/)).map((scope) => scope.trim()).filter(Boolean))].sort();
722
+ }
723
+ function normalizeOAuthScope(scope) {
724
+ const normalized = normalizeScopeList(scope ? [scope] : []);
725
+ return normalized.length ? normalized.join(" ") : void 0;
726
+ }
727
+ function hasRequiredOAuthScope(storedScope, requiredScope) {
728
+ const required = normalizeScopeList(requiredScope ? [requiredScope] : []);
729
+ if (required.length === 0) return true;
730
+ const stored = new Set(normalizeScopeList(storedScope ? [storedScope] : []));
731
+ if (stored.size === 0) return false;
732
+ return required.every((scope) => stored.has(scope));
733
+ }
734
+ function isGitHubApiUrl(upstreamUrl) {
735
+ return upstreamUrl.hostname.toLowerCase() === "api.github.com";
736
+ }
737
+ function base64Url(input) {
738
+ return Buffer.from(input).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
739
+ }
740
+ function getPrivateKey(envName) {
741
+ const raw = requireEnv(envName);
742
+ let key;
743
+ try {
744
+ key = createPrivateKey({
745
+ key: raw,
746
+ format: "pem"
747
+ });
748
+ } catch {
749
+ throw new GitHubPluginSetupError(`Invalid ${envName}: expected a PEM-encoded RSA private key`);
750
+ }
751
+ if (key.asymmetricKeyType !== "rsa") throw new GitHubPluginSetupError(`Invalid ${envName}: GitHub App signing requires an RSA private key`);
752
+ return key;
753
+ }
754
+ function createAppJwt(appId, privateKeyEnv) {
755
+ const now = Math.floor(Date.now() / 1e3);
756
+ const header = {
757
+ alg: "RS256",
758
+ typ: "JWT"
759
+ };
760
+ const payload = {
761
+ iat: now - 60,
762
+ exp: now + 540,
763
+ iss: appId
764
+ };
765
+ const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
766
+ const signer = createSign("RSA-SHA256");
767
+ signer.update(signingInput);
768
+ signer.end();
769
+ return `${signingInput}.${signer.sign(getPrivateKey(privateKeyEnv)).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")}`;
770
+ }
771
+ /** Send an authenticated request to the GitHub API. */
772
+ async function githubRequest(apiBase, path, params) {
773
+ const response = await fetch(`${apiBase}${path}`, {
774
+ method: params.method ?? "GET",
775
+ headers: {
776
+ Accept: "application/vnd.github+json",
777
+ Authorization: `Bearer ${params.token}`,
778
+ "X-GitHub-Api-Version": "2022-11-28",
779
+ ...params.body ? { "Content-Type": "application/json" } : void 0
780
+ },
781
+ ...params.body ? { body: JSON.stringify(params.body) } : void 0
782
+ });
783
+ const text = await response.text();
784
+ let parsed;
785
+ if (text) try {
786
+ parsed = JSON.parse(text);
787
+ } catch {
788
+ parsed = void 0;
789
+ }
790
+ if (!response.ok) throw new GitHubRequestError(isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"] : `GitHub API error ${response.status}`, response.status);
791
+ return parsed;
792
+ }
793
+ function buildOAuthTokenRequest(input) {
794
+ const payload = {
795
+ ...input.payload,
796
+ client_id: input.clientId,
797
+ client_secret: input.clientSecret
798
+ };
799
+ return {
800
+ headers: {
801
+ Accept: "application/json",
802
+ "Content-Type": "application/x-www-form-urlencoded"
803
+ },
804
+ body: new URLSearchParams(payload)
805
+ };
806
+ }
807
+ function parseOAuthResponseJson(responseText) {
808
+ if (!responseText.trim()) return;
809
+ try {
810
+ return JSON.parse(responseText);
811
+ } catch {
812
+ return;
813
+ }
814
+ }
815
+ function oauthErrorCode(data) {
816
+ return isRecord(data) && typeof data["error"] === "string" ? data["error"] : void 0;
817
+ }
818
+ function isRejectedRefreshError(errorCode) {
819
+ return errorCode === "bad_refresh_token" || errorCode === "invalid_grant";
820
+ }
821
+ function parseOAuthTokenResponse(data, requestedScope) {
822
+ if (!isRecord(data)) throw new Error("OAuth token response is invalid");
823
+ if (typeof data["access_token"] !== "string" || !data["access_token"].trim()) throw new Error("OAuth token response missing access_token");
824
+ if (typeof data["refresh_token"] !== "string" || !data["refresh_token"].trim()) throw new Error("OAuth token response missing refresh_token");
825
+ let scope = normalizeOAuthScope(requestedScope);
826
+ if (data["scope"] !== void 0) {
827
+ if (typeof data["scope"] !== "string") throw new Error("OAuth token response returned invalid scope");
828
+ scope = normalizeOAuthScope(data["scope"]) ?? scope;
829
+ }
830
+ const result = {
831
+ accessToken: data["access_token"],
832
+ refreshToken: data["refresh_token"],
833
+ ...scope ? { scope } : void 0
834
+ };
835
+ if (data["expires_in"] !== void 0) {
836
+ if (typeof data["expires_in"] !== "number" || !Number.isFinite(data["expires_in"]) || data["expires_in"] <= 0) throw new Error("OAuth token response returned invalid expires_in");
837
+ result.expiresAt = Date.now() + data["expires_in"] * 1e3;
838
+ }
839
+ if (data["refresh_token_expires_in"] !== void 0) {
840
+ if (typeof data["refresh_token_expires_in"] !== "number" || !Number.isFinite(data["refresh_token_expires_in"]) || data["refresh_token_expires_in"] <= 0) throw new Error("OAuth token response returned invalid refresh_token_expires_in");
841
+ result.refreshTokenExpiresAt = Date.now() + data["refresh_token_expires_in"] * 1e3;
842
+ }
843
+ return result;
844
+ }
845
+ async function refreshUserAccessToken(input) {
846
+ const request = buildOAuthTokenRequest({
847
+ clientId: requireEnv(input.clientIdEnv),
848
+ clientSecret: requireEnv(input.clientSecretEnv),
849
+ payload: {
850
+ grant_type: "refresh_token",
851
+ refresh_token: input.refreshToken
852
+ }
853
+ });
854
+ const response = await fetch("https://github.com/login/oauth/access_token", {
855
+ method: "POST",
856
+ headers: request.headers,
857
+ body: request.body,
858
+ signal: AbortSignal.timeout(USER_REFRESH_TIMEOUT_MS)
859
+ });
860
+ const responseData = parseOAuthResponseJson(await response.text());
861
+ const errorCode = oauthErrorCode(responseData);
862
+ if (isRejectedRefreshError(errorCode)) throw new GitHubUserRefreshRejectedError(`GitHub user token refresh rejected: ${errorCode}`);
863
+ if (!response.ok || errorCode) throw new Error(`GitHub user token refresh failed: ${response.status}${errorCode ? ` ${errorCode}` : ""}`);
864
+ try {
865
+ return parseOAuthTokenResponse(responseData, input.requestedScope);
866
+ } catch (error) {
867
+ if (error instanceof Error && error.message === "OAuth token response missing access_token") throw new GitHubUserRefreshRejectedError(error.message);
868
+ throw error;
869
+ }
870
+ }
871
+ function leaseExpiry(expiresAt) {
872
+ return expiresAt ? Math.min(expiresAt, Date.now() + MAX_LEASE_MS) : Date.now() + MAX_LEASE_MS;
873
+ }
874
+ function isGitSmartHttpDomain(domain) {
875
+ return domain.toLowerCase() === "github.com";
876
+ }
877
+ function authorizationFor(domain, token) {
878
+ if (isGitSmartHttpDomain(domain)) return `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
879
+ return `Bearer ${token}`;
880
+ }
881
+ function createCredentialLease(input) {
882
+ return {
883
+ type: "lease",
884
+ lease: {
885
+ ...input.account ? { account: input.account } : void 0,
886
+ ...input.authorization ? { authorization: input.authorization } : void 0,
887
+ expiresAt: new Date(input.expiresAtMs).toISOString(),
888
+ headerTransforms: (input.domains ?? (input.authorization ? GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS : GITHUB_CREDENTIAL_DOMAINS)).map((domain) => ({
889
+ domain,
890
+ headers: { Authorization: authorizationFor(domain, input.token) }
891
+ }))
892
+ }
893
+ };
894
+ }
895
+ function githubUserAuthorization(scope) {
896
+ return {
897
+ type: "oauth",
898
+ provider: "github",
899
+ ...scope ? { scope } : void 0
900
+ };
901
+ }
902
+ function credentialNeeded(message, scope, allowAuthorization = true) {
903
+ return {
904
+ type: "needed",
905
+ message,
906
+ ...allowAuthorization ? { authorization: githubUserAuthorization(scope) } : void 0
907
+ };
908
+ }
909
+ /** Return a credential result for invalid GitHub App configuration. */
910
+ function credentialUnavailable(message) {
911
+ return {
912
+ type: "unavailable",
913
+ message
914
+ };
915
+ }
916
+ function parseInstallationTokenResponse(data) {
917
+ if (!isRecord(data)) throw new Error("GitHub installation token response is invalid");
918
+ const token = data["token"];
919
+ if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
920
+ const expiresAt = data["expires_at"];
921
+ const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
922
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
923
+ return {
924
+ token,
925
+ expiresAtMs
926
+ };
927
+ }
928
+ function readInstallationPermissions(installation) {
929
+ if (!isRecord(installation) || !isRecord(installation["permissions"])) throw new Error("GitHub installation response missing permissions");
930
+ return readGrantPermissions(installation["permissions"]);
931
+ }
932
+ function decodeGitHubPathSegment(value) {
933
+ try {
934
+ const decoded = decodeURIComponent(value).trim();
935
+ return decoded && !decoded.includes("/") ? decoded : void 0;
936
+ } catch {
937
+ return;
938
+ }
939
+ }
940
+ /** Parse a GitHub repository from an API or Git URL. */
941
+ function githubRepositoryFromUrl(upstreamUrl) {
942
+ const segments = upstreamUrl.pathname.split("/").filter(Boolean);
943
+ if (isGitHubApiUrl(upstreamUrl) && segments[0]?.toLowerCase() === "repos") {
944
+ const owner = segments[1] ? decodeGitHubPathSegment(segments[1]) : void 0;
945
+ const name = segments[2] ? decodeGitHubPathSegment(segments[2]) : void 0;
946
+ return owner && name ? {
947
+ owner,
948
+ name
949
+ } : void 0;
950
+ }
951
+ if (upstreamUrl.hostname.toLowerCase() !== "github.com") return;
952
+ const owner = segments[0] ? decodeGitHubPathSegment(segments[0]) : void 0;
953
+ const rawName = segments[1]?.replace(/\.git$/i, "");
954
+ const name = rawName ? decodeGitHubPathSegment(rawName) : void 0;
955
+ return owner && name ? {
956
+ owner,
957
+ name
958
+ } : void 0;
959
+ }
960
+ /** Resolve the GitHub account associated with stored user tokens. */
961
+ async function resolveUserAccount(tokens) {
962
+ const account = await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken });
963
+ if (!isRecord(account)) throw new Error("GitHub user response is invalid");
964
+ const id = account["id"];
965
+ const login = account["login"];
966
+ if (typeof id !== "number" && typeof id !== "string" || typeof login !== "string" || !login.trim()) throw new Error("GitHub user response missing id or login");
967
+ const url = typeof account["html_url"] === "string" ? account["html_url"] : void 0;
968
+ return {
969
+ handle: login.trim(),
970
+ id: String(id),
971
+ label: login.trim(),
972
+ ...url ? { url } : void 0
973
+ };
974
+ }
975
+ /**
976
+ * List the email addresses GitHub verified for the user OAuth token.
977
+ *
978
+ * GitHub App user tokens need the App's "Email addresses" user permission.
979
+ * Return an empty list when the App does not have it.
980
+ */
981
+ async function listVerifiedUserEmails(tokens) {
982
+ let emails;
983
+ try {
984
+ emails = await githubRequest("https://api.github.com", "/user/emails", { token: tokens.accessToken });
985
+ } catch (error) {
986
+ if (error instanceof GitHubRequestError && (error.status === 403 || error.status === 404)) return [];
987
+ throw error;
988
+ }
989
+ if (!Array.isArray(emails)) throw new Error("GitHub user emails response is invalid");
990
+ return emails.flatMap((entry) => isRecord(entry) && entry["verified"] === true && typeof entry["email"] === "string" && entry["email"].trim() ? [entry["email"].trim()] : []);
991
+ }
992
+ async function tokensWithAccount(tokenSlot, stored, scope) {
993
+ if (stored.account) return {
994
+ ok: true,
995
+ tokens: stored
996
+ };
997
+ let account;
998
+ try {
999
+ account = await resolveUserAccount(stored);
1000
+ } catch (error) {
1001
+ if (error instanceof GitHubRequestError && (error.status === 401 || error.status === 403)) return {
1002
+ ok: false,
1003
+ result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
1004
+ };
1005
+ throw error;
1006
+ }
1007
+ const updated = {
1008
+ ...stored,
1009
+ account
1010
+ };
1011
+ await tokenSlot.set(updated);
1012
+ return {
1013
+ ok: true,
1014
+ tokens: updated
1015
+ };
1016
+ }
1017
+ function shouldRefreshUserToken(stored, now = Date.now()) {
1018
+ return stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS;
1019
+ }
1020
+ function canUseStoredUserToken(stored) {
1021
+ return stored.expiresAt === void 0 || stored.expiresAt > Date.now() && !shouldRefreshUserToken(stored);
1022
+ }
1023
+ /** Re-read under the token-slot refresh gate so concurrent callers reuse the winner's rotated tokens. */
1024
+ async function refreshUserTokensWithLock(tokenSlot, scope, options) {
1025
+ return await tokenSlot.withRefresh(async () => {
1026
+ const latest = await tokenSlot.get();
1027
+ if (!latest) return {
1028
+ ok: false,
1029
+ result: credentialNeeded("Connect your GitHub account.", scope)
1030
+ };
1031
+ if (!hasRequiredOAuthScope(latest.scope, scope)) return {
1032
+ ok: false,
1033
+ result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
1034
+ };
1035
+ if (canUseStoredUserToken(latest)) return {
1036
+ ok: true,
1037
+ tokens: latest
1038
+ };
1039
+ let refreshed;
1040
+ try {
1041
+ refreshed = await refreshUserAccessToken({
1042
+ clientIdEnv: options.clientIdEnv,
1043
+ clientSecretEnv: options.clientSecretEnv,
1044
+ refreshToken: latest.refreshToken,
1045
+ requestedScope: latest.scope ?? scope
1046
+ });
1047
+ } catch (error) {
1048
+ if (!(error instanceof GitHubUserRefreshRejectedError)) throw error;
1049
+ return {
1050
+ ok: false,
1051
+ result: credentialNeeded("Your GitHub authorization has expired.", scope)
1052
+ };
1053
+ }
1054
+ if (!hasRequiredOAuthScope(refreshed.scope, scope)) return {
1055
+ ok: false,
1056
+ result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
1057
+ };
1058
+ const refreshedTokens = {
1059
+ ...latest.refreshTokenExpiresAt ? { refreshTokenExpiresAt: latest.refreshTokenExpiresAt } : void 0,
1060
+ ...refreshed,
1061
+ ...latest.account ? { account: latest.account } : void 0
1062
+ };
1063
+ await tokenSlot.set(refreshedTokens);
1064
+ return {
1065
+ ok: true,
1066
+ tokens: refreshedTokens
1067
+ };
1068
+ });
1069
+ }
1070
+ /** Issue a bounded GitHub user credential for an approved grant. */
1071
+ async function issueUserCredential(ctx, options) {
1072
+ const scope = options.userScope;
1073
+ const tokenSlot = ctx.tokens.currentUser ?? ctx.tokens.credentialSubject;
1074
+ if (!tokenSlot) return credentialNeeded("GitHub write access requires a current user or delegated user credential subject.", scope, false);
1075
+ const stored = await tokenSlot.get();
1076
+ if (!stored) return credentialNeeded("GitHub write access requires user authorization.", scope);
1077
+ if (!hasRequiredOAuthScope(stored.scope, scope)) return credentialNeeded("Your GitHub authorization needs to be refreshed.", scope);
1078
+ const now = Date.now();
1079
+ if (stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS) {
1080
+ const refreshResult = await refreshUserTokensWithLock(tokenSlot, scope, options);
1081
+ if (!refreshResult.ok) return refreshResult.result;
1082
+ const withAccount = await tokensWithAccount(tokenSlot, refreshResult.tokens, scope);
1083
+ if (!withAccount.ok) return withAccount.result;
1084
+ return createCredentialLease({
1085
+ account: withAccount.tokens.account,
1086
+ token: withAccount.tokens.accessToken,
1087
+ expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
1088
+ authorization: githubUserAuthorization(scope)
1089
+ });
1090
+ }
1091
+ if (stored.expiresAt === void 0 || stored.expiresAt > Date.now()) {
1092
+ const withAccount = await tokensWithAccount(tokenSlot, stored, scope);
1093
+ if (!withAccount.ok) return withAccount.result;
1094
+ return createCredentialLease({
1095
+ account: withAccount.tokens.account,
1096
+ token: withAccount.tokens.accessToken,
1097
+ expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
1098
+ authorization: githubUserAuthorization(scope)
1099
+ });
1100
+ }
1101
+ return credentialNeeded("Your GitHub authorization has expired.", scope);
1102
+ }
1103
+ /** Issue a bounded raw token for plugin-owned GitHub API calls. */
1104
+ async function issueInstallationToken(options) {
1105
+ const appId = requireEnv(options.appIdEnv);
1106
+ const installationIdRaw = requireEnv(options.installationIdEnv);
1107
+ const installationId = Number(installationIdRaw);
1108
+ if (!Number.isSafeInteger(installationId) || installationId <= 0) throw new GitHubPluginSetupError(`Invalid ${options.installationIdEnv}`);
1109
+ const appJwt = createAppJwt(appId, options.privateKeyEnv);
1110
+ const permissions = "permissions" in options ? options.permissions : typeof options.loadPermissions === "function" ? await options.loadPermissions({
1111
+ appJwt,
1112
+ installationId
1113
+ }) : void 0;
1114
+ const repositories = "repositories" in options ? options.repositories : void 0;
1115
+ const repositoryIds = "repositoryIds" in options ? options.repositoryIds : void 0;
1116
+ const body = {
1117
+ ...permissions ? { permissions } : void 0,
1118
+ ...repositories ? { repositories } : void 0,
1119
+ ...repositoryIds ? { repository_ids: repositoryIds } : void 0
1120
+ };
1121
+ const parsedToken = parseInstallationTokenResponse(await githubRequest("https://api.github.com", `/app/installations/${installationId}/access_tokens`, {
1122
+ method: "POST",
1123
+ token: appJwt,
1124
+ body
1125
+ }));
1126
+ return {
1127
+ expiresAtMs: Math.min(parsedToken.expiresAtMs, Date.now() + MAX_LEASE_MS),
1128
+ token: parsedToken.token
1129
+ };
1130
+ }
1131
+ /** Issue a bounded GitHub App installation credential. */
1132
+ async function issueInstallationCredential(options) {
1133
+ const token = await issueInstallationToken(options);
1134
+ return createCredentialLease({
1135
+ token: token.token,
1136
+ expiresAtMs: token.expiresAtMs
1137
+ });
1138
+ }
1139
+ /**
1140
+ * Issue the credential for one GitHub grant that host egress selected. Only
1141
+ * the `issueCredential` hook may call this. Other code reads and writes GitHub
1142
+ * through host egress.
1143
+ */
1144
+ async function issueGitHubCredential(ctx, options) {
1145
+ const installation = {
1146
+ appIdEnv: options.appIdEnv,
1147
+ installationIdEnv: options.installationIdEnv,
1148
+ privateKeyEnv: options.privateKeyEnv
1149
+ };
1150
+ try {
1151
+ if (ctx.grant.name === "installation-read") return await issueInstallationCredential({
1152
+ ...installation,
1153
+ ...options.readPermissions
1154
+ });
1155
+ if (ctx.grant.name === "installation-write") return await issueInstallationCredential(installation);
1156
+ if (USER_TOKEN_GRANTS.has(ctx.grant.name)) return await issueUserCredential(ctx, options);
1157
+ } catch (error) {
1158
+ if (error instanceof GitHubPluginSetupError) return credentialUnavailable(error.message);
1159
+ throw error;
1160
+ }
1161
+ throw new Error(`GitHub plugin cannot issue unknown grant "${ctx.grant.name}".`);
1162
+ }
1163
+ /** Cache the installation's read permissions for one lease period. */
1164
+ function createPermissionCache() {
1165
+ let cached;
1166
+ let pending;
1167
+ return async ({ appJwt, installationId }) => {
1168
+ if (cached && cached.expiresAtMs > Date.now()) return cached.permissions;
1169
+ pending ??= githubRequest("https://api.github.com", `/app/installations/${installationId}`, { token: appJwt }).then((installation) => {
1170
+ const permissions = readInstallationPermissions(installation);
1171
+ cached = {
1172
+ expiresAtMs: Date.now() + MAX_LEASE_MS,
1173
+ permissions
1174
+ };
1175
+ return permissions;
1176
+ }).finally(() => {
1177
+ pending = void 0;
1178
+ });
1179
+ return await pending;
1180
+ };
1181
+ }
1182
+ // src/webhooks/event-targets.ts
1183
+ /**
1184
+ * The user who sent a webhook. GitHub authenticates this user, so on a comment
1185
+ * or review it is the author, and on an issue update it made the change.
1186
+ * Match on the numeric id; logins can be renamed and reused.
1187
+ */
1188
+ const gitHubSenderSchema = z.object({
1189
+ id: z.number(),
1190
+ login: z.string().min(1)
1191
+ });
1192
+ /** Trusted event data that names who sent a webhook. */
1193
+ function gitHubSenderData(sender) {
1194
+ return {
1195
+ senderId: sender?.id,
1196
+ senderLogin: sender?.login
1197
+ };
1198
+ }
1199
+ /** The GitHub user who did what an Event describes, when GitHub names one. */
1200
+ function gitHubDoneBy(login) {
1201
+ const handle = login?.trim();
1202
+ return handle ? { doneBy: {
1203
+ provider: "github",
1204
+ handle
1205
+ } } : void 0;
1206
+ }
1207
+ /** The text of a webhook value, or undefined when it is missing or blank. */
1208
+ function nonBlank(value) {
1209
+ return value?.trim() || void 0;
1210
+ }
1211
+ /** The title and body of an issue or pull request, as untrusted text. */
1212
+ function titleAndBodyText(item) {
1213
+ const parts = [item.title ? `Title: ${item.title}` : void 0, nonBlank(item.body)].filter((part) => part !== void 0);
1214
+ return parts.length > 0 ? parts.join("\n\n") : void 0;
1215
+ }
1216
+ /** Convert an optional provider timestamp for receipt-time fallback ordering. */
1217
+ function providerTime(value) {
1218
+ if (!value) return void 0;
1219
+ const parsed = Date.parse(value);
1220
+ return Number.isFinite(parsed) ? parsed : void 0;
1221
+ }
1222
+ /**
1223
+ * Drop missing values from event data. A filter on a value that GitHub did not
1224
+ * send then does not match.
1225
+ */
1226
+ function definedValues(data) {
1227
+ return Object.fromEntries(Object.entries(data).filter(([, value]) => value !== void 0));
1228
+ }
1229
+ /** Build the event key for one event type from one webhook delivery. */
1230
+ function gitHubEventKey(deliveryId, eventType) {
1231
+ return `github:${deliveryId}:${eventType}`;
1232
+ }
1233
+ /**
1234
+ * Address a pull request event through both the pull request and its
1235
+ * repository. Only the pull request copy keeps `terminal`, so a terminal
1236
+ * event never completes a repository Watch.
1237
+ */
1238
+ function pullRequestTargets(event, repo) {
1239
+ const { terminal: _terminal, ...repositoryEvent } = event;
1240
+ return [event, {
1241
+ ...repositoryEvent,
1242
+ identifier: gitHubRepositoryResource({ repo }).identifier
1243
+ }];
1244
+ }
1245
+ // src/webhooks/fail-open-log.ts
1246
+ /**
1247
+ * Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
1248
+ * not a Junior bug, so it is a warning with the HTTP status. Other failures
1249
+ * stay errors.
1250
+ */
1251
+ function logFailOpenFailure(log, message, error, metadata) {
1252
+ const attributes = {
1253
+ ...metadata,
1254
+ errorType: error instanceof Error ? error.name : "UnknownError"
1255
+ };
1256
+ if (error instanceof GitHubRequestError && error.status >= 500) {
1257
+ log?.warn(message, {
1258
+ ...attributes,
1259
+ "http.response.status_code": error.status
1260
+ });
1261
+ return;
1262
+ }
1263
+ log?.error(message, attributes);
1264
+ }
1265
+ // src/webhooks/check-suite.ts
1266
+ /** Match keys that need a pull request API load on check suite events. */
1267
+ const CHECK_SUITE_PULL_REQUEST_MATCH_KEYS = /* @__PURE__ */ new Set([
1268
+ "isDraft",
1269
+ "openerEmail",
1270
+ "openerRole",
1271
+ "openerUsername"
1272
+ ]);
1273
+ /**
1274
+ * Match keys whose values load after the webhook decides whether to read the
1275
+ * check suites, so a match check then cannot rule out a filter on them.
1276
+ */
1277
+ const LATE_MATCH_KEYS = /* @__PURE__ */ new Set([...CHECK_SUITE_PULL_REQUEST_MATCH_KEYS, "authors"]);
1278
+ /**
1279
+ * Check suite pull_requests use GitHub's CheckRunPullRequest shape:
1280
+ * url, id, number, head/base with repo { id, url, name }.
1281
+ * No draft, author, or full_name on those objects.
1282
+ * @see https://docs.github.com/en/webhooks/webhook-events-and-payloads#check_suite
1283
+ */
1284
+ const checkRunRepoRefSchema = z.object({
1285
+ id: z.number(),
1286
+ name: z.string().min(1),
1287
+ url: z.string().min(1)
1288
+ }).passthrough();
1289
+ const checkRunPullRequestSideSchema = z.object({
1290
+ ref: z.string().optional(),
1291
+ repo: checkRunRepoRefSchema,
1292
+ sha: z.string().optional()
1293
+ }).passthrough();
1294
+ const checkRunPullRequestSchema = z.object({
1295
+ base: checkRunPullRequestSideSchema,
1296
+ head: checkRunPullRequestSideSchema.optional(),
1297
+ id: z.number().optional(),
1298
+ number: z.number(),
1299
+ url: z.string().optional()
1300
+ }).passthrough();
1301
+ const repositorySchema$1 = z.object({
1302
+ full_name: z.string().min(1),
1303
+ id: z.number(),
1304
+ name: z.string().min(1),
1305
+ owner: z.object({ login: z.string().min(1) }).passthrough()
1306
+ }).passthrough();
1307
+ const checkSuiteWebhookSchema = z.object({
1308
+ action: z.string(),
1309
+ check_suite: z.object({
1310
+ app: z.object({
1311
+ name: z.string().optional().nullable(),
1312
+ slug: z.string().optional().nullable()
1313
+ }).optional().nullable(),
1314
+ conclusion: z.string().optional().nullable(),
1315
+ /** Branch name for the suite head commit when GitHub sends it. */
1316
+ head_branch: z.string().optional().nullable(),
1317
+ head_sha: z.string().optional(),
1318
+ id: z.number().optional(),
1319
+ latest_check_runs_count: z.number().optional().nullable(),
1320
+ pull_requests: z.array(checkRunPullRequestSchema)
1321
+ }),
1322
+ repository: repositorySchema$1
1323
+ });
1324
+ /** List check suites for a commit: { total_count, check_suites: CheckSuite[] }. */
1325
+ const checkSuitesListResponseSchema = z.object({
1326
+ check_suites: z.array(z.object({
1327
+ app: z.object({ slug: z.string().nullable().optional() }).nullable().optional(),
1328
+ conclusion: z.string().nullable().optional(),
1329
+ id: z.number(),
1330
+ latest_check_runs_count: z.number().nullable().optional(),
1331
+ status: z.string().nullable().optional()
1332
+ })),
1333
+ total_count: z.number()
1334
+ });
1335
+ /** List check runs in a suite: { check_runs: CheckRun[] }. */
1336
+ const checkRunsListResponseSchema = z.object({ check_runs: z.array(z.unknown()).optional() }).passthrough();
1337
+ /**
1338
+ * Keep only pull requests whose base repo is the check suite repository.
1339
+ * GitHub attaches every open PR with the same head sha, including PRs based on forks.
1340
+ * Compare repository ids from the webhook payload — no URL parsing.
1341
+ */
1342
+ function isCheckSuiteRepositoryPullRequest(pullRequest, repositoryId) {
1343
+ return pullRequest.base.repo.id === repositoryId;
1344
+ }
1345
+ const CHECKS_PASSED = "pull_request.checks.passed";
1346
+ /** Suite conclusions that count as passing for `pull_request.checks.passed`. */
1347
+ const PASSING_SUITE_CONCLUSIONS = /* @__PURE__ */ new Set([
1348
+ "neutral",
1349
+ "skipped",
1350
+ "success"
1351
+ ]);
1352
+ /** Pages of 100 check suites to read for one commit before giving up. */
1353
+ const MAX_CHECK_SUITE_PAGES = 10;
1354
+ /** Map a completed check suite conclusion to the event type we publish. */
1355
+ function checkSuiteEventType(conclusion) {
1356
+ if (conclusion === "failure" || conclusion === "timed_out") return "pull_request.checks.failed";
1357
+ if (conclusion === "success") return "pull_request.checks.recovered";
1358
+ }
1359
+ /**
1360
+ * Event types that a completed suite may publish. Any passing suite can be
1361
+ * the last one on its commit, so each one is a `pull_request.checks.passed`
1362
+ * candidate. The webhook keeps that event only when every suite passed.
1363
+ */
1364
+ function checkSuiteEventTypes(conclusion) {
1365
+ const eventType = checkSuiteEventType(conclusion);
1366
+ const eventTypes = eventType ? [eventType] : [];
1367
+ if (PASSING_SUITE_CONCLUSIONS.has(conclusion ?? "")) eventTypes.push(CHECKS_PASSED);
1368
+ return eventTypes;
1369
+ }
1370
+ /** True when a GitHub API call failed with HTTP 404. */
1371
+ function isGitHubNotFoundError(error) {
1372
+ return error instanceof Error && error.name === "GitHubRequestError" && "status" in error && error.status === 404;
1373
+ }
1374
+ const FAILING_CHECK_CONCLUSIONS = /* @__PURE__ */ new Set([
1375
+ "failure",
1376
+ "timed_out",
1377
+ "cancelled",
1378
+ "action_required",
1379
+ "startup_failure"
1380
+ ]);
1381
+ /** Build a browser URL for one check suite. GitHub does not send html_url. */
1382
+ function buildCheckSuiteUrl(args) {
1383
+ return `https://github.com/${args.repo}/commit/${args.headSha}/checks?check_suite_id=${args.checkSuiteId}`;
1384
+ }
1385
+ /** Collapse provider free text into one short summary fragment. */
1386
+ function oneLineLabel(value, maxLength = 80) {
1387
+ return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength);
1388
+ }
1389
+ /** Non-empty branch name from a webhook string. */
1390
+ function checkSuiteHeadBranch(value) {
1391
+ const branch = value?.trim();
1392
+ return branch ? branch : void 0;
1393
+ }
1394
+ /**
1395
+ * Trusted data on every check suite event. `pullRequest` is missing when
1396
+ * GitHub links the suite to no pull request, such as on the main branch.
1397
+ * `commitSha` is missing when GitHub sends no full SHA. `suiteConclusion`
1398
+ * stays as a detail, not a filter: the event type already tells failed from
1399
+ * recovered.
1400
+ */
1401
+ const checkSuiteEventDataSchema = z.object({
1402
+ repo: gitHubRepoDataSchema,
1403
+ pullRequest: z.number().optional(),
1404
+ commitSha: gitHubCommitShaDataSchema.optional(),
1405
+ suiteConclusion: z.string().min(1),
1406
+ isDraft: z.boolean().optional(),
1407
+ openerUsername: z.string().min(1).optional(),
1408
+ openerEmail: z.string().min(1).optional(),
1409
+ headBranch: z.string().min(1).optional(),
1410
+ checkSuiteId: z.number().optional(),
1411
+ checkSuiteUrl: z.string().min(1).optional(),
1412
+ appName: z.string().min(1).optional(),
1413
+ latestCheckRunsCount: z.number().optional(),
1414
+ failingChecks: z.array(z.object({
1415
+ conclusion: z.string(),
1416
+ htmlUrl: z.string().optional(),
1417
+ checkRunId: z.number()
1418
+ }).strict()).optional()
1419
+ }).strict();
1420
+ /** Build the trusted data and summary for one check-suite event. */
1421
+ function buildCheckSuiteEvent(args) {
1422
+ const pullRequestNumber = args.pullRequestNumber;
1423
+ const resource = pullRequestNumber === void 0 ? gitHubRepositoryResource({ repo: args.repo }) : gitHubPullRequestResource({
1424
+ number: pullRequestNumber,
1425
+ repo: args.repo
1426
+ });
1427
+ const shortSha = args.headSha?.slice(0, 12);
1428
+ const failingChecks = (args.failingChecks ?? []).slice(0, 12);
1429
+ const failingCount = failingChecks.length;
1430
+ const branchSuffix = args.headBranch ? ` on ${args.headBranch}` : "";
1431
+ const incidents = args.eventType === "pull_request.checks.failed" ? args.githubIncidents ?? [] : [];
1432
+ const incidentSuffix = incidents.length > 0 ? ` githubstatus.com lists ${incidents.length} open or recent GitHub incident${incidents.length === 1 ? "" : "s"}.` : "";
1433
+ const shaSuffix = shortSha ? ` for ${shortSha}` : "";
1434
+ const trustedSummary = args.eventType === "pull_request.checks.failed" ? `${resource.label} checks failed${failingCount > 0 ? ` (${failingCount})` : ""}${shaSuffix}${branchSuffix}.${incidentSuffix}` : args.eventType === CHECKS_PASSED ? `${resource.label} all check suites passed${shaSuffix}${branchSuffix}.` : `${resource.label} check suite recovered${shaSuffix}${branchSuffix}.`;
1435
+ const data = checkSuiteEventDataSchema.parse(definedValues({
1436
+ repo: args.repo,
1437
+ pullRequest: pullRequestNumber,
1438
+ commitSha: gitHubCommitShaDataSchema.safeParse(args.headSha).data,
1439
+ suiteConclusion: args.suiteConclusion,
1440
+ isDraft: args.isDraft,
1441
+ openerUsername: args.openerUsername,
1442
+ openerEmail: args.openerEmail,
1443
+ headBranch: args.headBranch,
1444
+ checkSuiteId: args.checkSuiteId,
1445
+ checkSuiteUrl: args.checkSuiteId !== void 0 && args.headSha ? buildCheckSuiteUrl({
1446
+ checkSuiteId: args.checkSuiteId,
1447
+ headSha: args.headSha,
1448
+ repo: args.repo
1449
+ }) : void 0,
1450
+ appName: args.appName ? oneLineLabel(args.appName, 120) : void 0,
1451
+ latestCheckRunsCount: args.latestCheckRunsCount,
1452
+ failingChecks: args.eventType === "pull_request.checks.failed" && failingCount > 0 ? failingChecks.map((check) => ({
1453
+ conclusion: check.conclusion,
1454
+ ...check.htmlUrl ? { htmlUrl: check.htmlUrl } : void 0,
1455
+ checkRunId: check.checkRunId
1456
+ })) : void 0
1457
+ }));
1458
+ const untrustedParts = args.eventType === "pull_request.checks.failed" ? failingChecks.map((check) => {
1459
+ const name = oneLineLabel(check.name);
1460
+ if (!name) return void 0;
1461
+ return check.htmlUrl ? `${name}: ${check.htmlUrl}` : name;
1462
+ }).filter((part) => part !== void 0) : [];
1463
+ const untrustedSections = [...untrustedParts.length > 0 ? [[`Failed checks:`, ...untrustedParts.map((part) => `- ${part}`)].join("\n")] : [], ...incidents.length > 0 ? [["GitHub status incidents:", ...incidents.map((incident) => `- ${oneLineLabel(incident.name, 160)} (${incident.status}; ${incident.components.join(", ") || "no components"}; started ${incident.startedAt}${incident.resolvedAt ? `, resolved ${incident.resolvedAt}` : ""}): ${incident.url}`)].join("\n")] : []];
1464
+ const untrustedText = untrustedSections.length > 0 ? untrustedSections.join("\n\n") : void 0;
1465
+ return {
1466
+ eventKey: args.eventType === CHECKS_PASSED && args.headSha ? `github:${CHECKS_PASSED}:${resource.identifier}:${args.headSha.toLowerCase()}` : gitHubEventKey(args.deliveryId, pullRequestNumber === void 0 ? args.eventType : `${args.eventType}:${pullRequestNumber}`),
1467
+ eventType: args.eventType,
1468
+ occurredAtMs: Date.now(),
1469
+ identifier: resource.identifier,
1470
+ trustedSummary,
1471
+ data,
1472
+ ...untrustedText ? { untrustedText } : void 0
1473
+ };
1474
+ }
1475
+ /** Keep only failed check runs from one suite. */
1476
+ function selectFailingChecks(checkRuns, options) {
1477
+ if (!Array.isArray(checkRuns)) return [];
1478
+ const failing = [];
1479
+ for (const run of checkRuns) {
1480
+ if (!run || typeof run !== "object" || Array.isArray(run)) continue;
1481
+ const record = run;
1482
+ if (options?.checkSuiteId !== void 0) {
1483
+ const suite = record["check_suite"];
1484
+ const suiteId = suite && typeof suite === "object" && !Array.isArray(suite) && typeof suite.id === "number" ? suite.id : void 0;
1485
+ if (suiteId !== void 0 && suiteId !== options.checkSuiteId) continue;
1486
+ }
1487
+ const conclusion = typeof record["conclusion"] === "string" ? record["conclusion"] : void 0;
1488
+ const name = typeof record["name"] === "string" ? record["name"].trim() : "";
1489
+ const checkRunId = typeof record["id"] === "number" && Number.isSafeInteger(record["id"]) ? record["id"] : void 0;
1490
+ if (!conclusion || !FAILING_CHECK_CONCLUSIONS.has(conclusion)) continue;
1491
+ if (!name || checkRunId === void 0) continue;
1492
+ const htmlUrl = typeof record["html_url"] === "string" && record["html_url"].length > 0 ? record["html_url"] : void 0;
1493
+ failing.push({
1494
+ checkRunId,
1495
+ conclusion,
1496
+ ...htmlUrl ? { htmlUrl } : void 0,
1497
+ name
1498
+ });
1499
+ }
1500
+ return failing.slice(0, 12);
1501
+ }
1502
+ /** Normalize a completed check suite for attached PRs, or the repository alone. */
1503
+ function normalizeCheckSuiteEvents(deliveryId, body, options) {
1504
+ const parsed = checkSuiteWebhookSchema.safeParse(body);
1505
+ if (!parsed.success || parsed.data.action !== "completed") return [];
1506
+ const conclusion = parsed.data.check_suite.conclusion;
1507
+ const eventType = checkSuiteEventType(conclusion);
1508
+ const eventTypes = checkSuiteEventTypes(conclusion).filter((type) => type !== CHECKS_PASSED || options?.allCheckSuitesPassed);
1509
+ if (eventTypes.length === 0 || typeof conclusion !== "string") return [];
1510
+ const suite = parsed.data.check_suite;
1511
+ const appName = suite.app?.name?.trim() || suite.app?.slug?.trim() || void 0;
1512
+ const headBranch = checkSuiteHeadBranch(suite.head_branch);
1513
+ const headSha = typeof suite.head_sha === "string" && /^[0-9a-f]{7,40}$/i.test(suite.head_sha) ? suite.head_sha : void 0;
1514
+ const repository = parsed.data.repository;
1515
+ const repo = repository.full_name;
1516
+ const shared = {
1517
+ appName,
1518
+ checkSuiteId: suite.id,
1519
+ deliveryId,
1520
+ failingChecks: eventType === "pull_request.checks.failed" ? options?.failingChecks : void 0,
1521
+ githubIncidents: eventType === "pull_request.checks.failed" ? options?.githubIncidents : void 0,
1522
+ headSha,
1523
+ latestCheckRunsCount: typeof suite.latest_check_runs_count === "number" ? suite.latest_check_runs_count : void 0,
1524
+ repo,
1525
+ suiteConclusion: conclusion
1526
+ };
1527
+ const sameRepoPullRequests = suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id));
1528
+ if (sameRepoPullRequests.length === 0) return eventTypes.map((type) => buildCheckSuiteEvent({
1529
+ ...shared,
1530
+ eventType: type,
1531
+ ...headBranch ? { headBranch } : void 0
1532
+ }));
1533
+ return eventTypes.flatMap((type) => sameRepoPullRequests.flatMap((pullRequest) => {
1534
+ const facts = options?.pullRequestFactsByNumber?.[pullRequest.number];
1535
+ const pullRequestHeadBranch = checkSuiteHeadBranch(pullRequest.head?.ref) ?? headBranch;
1536
+ return pullRequestTargets(buildCheckSuiteEvent({
1537
+ ...shared,
1538
+ eventType: type,
1539
+ ...facts?.openerEmail ? { openerEmail: facts.openerEmail } : void 0,
1540
+ ...facts?.openerUsername ? { openerUsername: facts.openerUsername } : void 0,
1541
+ ...pullRequestHeadBranch ? { headBranch: pullRequestHeadBranch } : void 0,
1542
+ ...typeof facts?.isDraft === "boolean" ? { isDraft: facts.isDraft } : void 0,
1543
+ pullRequestNumber: pullRequest.number
1544
+ }), repo);
1545
+ }));
1546
+ }
1547
+ /** The same-repository pull requests of one completed check suite. */
1548
+ function checkSuitePullRequests(body) {
1549
+ const parsed = checkSuiteWebhookSchema.safeParse(body);
1550
+ if (!parsed.success || parsed.data.action !== "completed") return [];
1551
+ const repository = parsed.data.repository;
1552
+ return parsed.data.check_suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)).map((pullRequest) => ({
1553
+ number: pullRequest.number,
1554
+ repositoryFullName: repository.full_name
1555
+ }));
1556
+ }
1557
+ /** Identifiers and event types one completed check suite may publish. */
1558
+ function parseCheckSuitePublishTargets(body) {
1559
+ const parsed = checkSuiteWebhookSchema.safeParse(body);
1560
+ if (!parsed.success || parsed.data.action !== "completed") return void 0;
1561
+ const eventTypes = checkSuiteEventTypes(parsed.data.check_suite.conclusion);
1562
+ if (eventTypes.length === 0) return void 0;
1563
+ const repository = parsed.data.repository;
1564
+ const repo = repository.full_name;
1565
+ const identifiers = /* @__PURE__ */ new Set([gitHubRepositoryResource({ repo }).identifier]);
1566
+ for (const pullRequest of parsed.data.check_suite.pull_requests) {
1567
+ if (!isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)) continue;
1568
+ identifiers.add(gitHubPullRequestResource({
1569
+ number: pullRequest.number,
1570
+ repo
1571
+ }).identifier);
1572
+ }
1573
+ return {
1574
+ data: { repo: gitHubRepoDataSchema.parse(repo) },
1575
+ eventTypes,
1576
+ identifiers: [...identifiers]
1577
+ };
1578
+ }
1579
+ /**
1580
+ * True when a Watch or event automation may want `pull_request.checks.passed`
1581
+ * for this check suite, so the webhook reads the other suites on the commit
1582
+ * only then. A filter on a value that loads later counts as a match, so the
1583
+ * check never drops an Event that someone wants.
1584
+ */
1585
+ async function wantsCheckSuitePassed(args) {
1586
+ const targets = parseCheckSuitePublishTargets(args.body);
1587
+ if (!args.hasMatch || !targets?.eventTypes.includes(CHECKS_PASSED)) return false;
1588
+ if ((await args.neededMatchKeys?.({
1589
+ ...targets,
1590
+ eventTypes: [CHECKS_PASSED]
1591
+ }) ?? []).some((key) => LATE_MATCH_KEYS.has(key))) return true;
1592
+ return await args.hasMatch(normalizeCheckSuiteEvents(args.deliveryId, args.body, { allCheckSuitesPassed: true }).filter((event) => event.eventType === CHECKS_PASSED));
1593
+ }
1594
+ /** Read which check suite values still need a GitHub API load. */
1595
+ function parseCheckSuiteFactsTarget(body, options) {
1596
+ const parsed = checkSuiteWebhookSchema.safeParse(body);
1597
+ if (!parsed.success || parsed.data.action !== "completed") return void 0;
1598
+ const conclusion = parsed.data.check_suite.conclusion;
1599
+ if (checkSuiteEventTypes(conclusion).length === 0) return void 0;
1600
+ const headSha = parsed.data.check_suite.head_sha;
1601
+ const checkSuiteId = parsed.data.check_suite.id;
1602
+ if (typeof headSha !== "string" || !/^[0-9a-f]{7,40}$/i.test(headSha) || typeof checkSuiteId !== "number") return;
1603
+ const repository = parsed.data.repository;
1604
+ const pullRequestNumbers = [...new Set(parsed.data.check_suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)).map((pullRequest) => pullRequest.number))];
1605
+ const loadFailingChecks = conclusion === "failure" || conclusion === "timed_out";
1606
+ const loadPullRequestFacts = Boolean(options?.loadPullRequestFacts && pullRequestNumbers.length > 0);
1607
+ const loadCheckSuites = Boolean(options?.loadCheckSuites && PASSING_SUITE_CONCLUSIONS.has(conclusion ?? ""));
1608
+ if (!loadFailingChecks && !loadPullRequestFacts && !loadCheckSuites) return;
1609
+ return {
1610
+ checkSuiteId,
1611
+ headSha,
1612
+ loadCheckSuites,
1613
+ loadFailingChecks,
1614
+ loadPullRequestFacts,
1615
+ owner: repository.owner.login,
1616
+ pullRequestNumbers,
1617
+ repoName: repository.name
1618
+ };
1619
+ }
1620
+ function checkRunsFromResponse(value) {
1621
+ const parsed = checkRunsListResponseSchema.safeParse(value);
1622
+ if (!parsed.success) return [];
1623
+ return parsed.data.check_runs ?? [];
1624
+ }
1625
+ function pullRequestFactsFromResponse(value) {
1626
+ if (!isRecord(value)) return void 0;
1627
+ const facts = {};
1628
+ if (typeof value["draft"] === "boolean") facts.isDraft = value["draft"];
1629
+ const user = value["user"];
1630
+ if (isRecord(user)) {
1631
+ const username = typeof user["login"] === "string" ? user["login"].trim() : void 0;
1632
+ if (username) facts.openerUsername = username;
1633
+ const email = typeof user["email"] === "string" ? user["email"].trim() : void 0;
1634
+ if (email) facts.openerEmail = email;
1635
+ }
1636
+ return Object.keys(facts).length > 0 ? facts : void 0;
1637
+ }
1638
+ /** True when active match filters need pull request fields from the API. */
1639
+ function needsCheckSuitePullRequestFacts(matchKeys) {
1640
+ for (const key of matchKeys) if (CHECK_SUITE_PULL_REQUEST_MATCH_KEYS.has(key)) return true;
1641
+ return false;
1642
+ }
1643
+ /**
1644
+ * Read every check suite on one commit and return whether all of them passed.
1645
+ * The suite that sent the webhook already passed. GitHub makes a queued suite
1646
+ * for each app that can write checks, even when the app never adds a check
1647
+ * run, so a queued suite with no check runs does not count. GitHub Actions
1648
+ * makes a suite only for a workflow that runs, and its suite can be queued
1649
+ * before it adds runs, so its suites always count. With more suites than the
1650
+ * pages read, the answer is false.
1651
+ */
1652
+ async function loadAllCheckSuitesPassed(args) {
1653
+ const suites = [];
1654
+ let totalCount = 0;
1655
+ for (let page = 1; page <= MAX_CHECK_SUITE_PAGES; page += 1) {
1656
+ const response = checkSuitesListResponseSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repoName)}/commits/${args.headSha}/check-suites?per_page=100&page=${page}`, { token: args.token }));
1657
+ suites.push(...response.check_suites);
1658
+ totalCount = response.total_count;
1659
+ if (suites.length >= totalCount || response.check_suites.length === 0) break;
1660
+ }
1661
+ if (suites.length < totalCount) return false;
1662
+ return suites.every((suite) => suite.id === args.checkSuiteId || suite.status === "queued" && suite.latest_check_runs_count === 0 && suite.app?.slug !== "github-actions" || suite.status === "completed" && PASSING_SUITE_CONCLUSIONS.has(suite.conclusion ?? ""));
1663
+ }
1664
+ /**
1665
+ * Load failed check runs, whether every check suite on the commit passed,
1666
+ * and optional pull request match fields.
1667
+ */
1668
+ async function loadCheckSuiteFacts(args) {
1669
+ const target = parseCheckSuiteFactsTarget(args.body, {
1670
+ loadCheckSuites: args.loadCheckSuites,
1671
+ loadPullRequestFacts: args.loadPullRequestFacts
1672
+ });
1673
+ if (!target) return void 0;
1674
+ const facts = {};
1675
+ if (target.loadFailingChecks) try {
1676
+ const token = await issueInstallationToken({
1677
+ appIdEnv: args.appIdEnv,
1678
+ installationIdEnv: args.installationIdEnv,
1679
+ permissions: { checks: "read" },
1680
+ privateKeyEnv: args.privateKeyEnv,
1681
+ repositories: [target.repoName]
1682
+ });
1683
+ const failing = selectFailingChecks(checkRunsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/check-suites/${target.checkSuiteId}/check-runs?filter=latest&per_page=100`, { token: token.token })), { checkSuiteId: target.checkSuiteId });
1684
+ if (failing.length > 0) facts.failingChecks = failing;
1685
+ } catch (error) {
1686
+ logFailOpenFailure(args.log, "GitHub check suite load failed", error, {
1687
+ checkSuiteId: target.checkSuiteId,
1688
+ repository: `${target.owner}/${target.repoName}`
1689
+ });
1690
+ }
1691
+ if (target.loadCheckSuites) try {
1692
+ const token = await issueInstallationToken({
1693
+ appIdEnv: args.appIdEnv,
1694
+ installationIdEnv: args.installationIdEnv,
1695
+ permissions: { checks: "read" },
1696
+ privateKeyEnv: args.privateKeyEnv,
1697
+ repositories: [target.repoName]
1698
+ });
1699
+ if (await loadAllCheckSuitesPassed({
1700
+ checkSuiteId: target.checkSuiteId,
1701
+ headSha: target.headSha,
1702
+ owner: target.owner,
1703
+ repoName: target.repoName,
1704
+ token: token.token
1705
+ })) facts.allCheckSuitesPassed = true;
1706
+ } catch (error) {
1707
+ logFailOpenFailure(args.log, "GitHub commit check suites load failed", error, {
1708
+ checkSuiteId: target.checkSuiteId,
1709
+ repository: `${target.owner}/${target.repoName}`
1710
+ });
1711
+ }
1712
+ if (target.loadFailingChecks && args.loadGitHubIncidents) try {
1713
+ const incidents = await args.loadGitHubIncidents();
1714
+ if (incidents.length > 0) facts.githubIncidents = incidents;
1715
+ } catch (error) {
1716
+ logFailOpenFailure(args.log, "GitHub status load failed", error, {});
1717
+ }
1718
+ if (target.loadPullRequestFacts) try {
1719
+ const token = await issueInstallationToken({
1720
+ appIdEnv: args.appIdEnv,
1721
+ installationIdEnv: args.installationIdEnv,
1722
+ permissions: { pull_requests: "read" },
1723
+ privateKeyEnv: args.privateKeyEnv,
1724
+ repositories: [target.repoName]
1725
+ });
1726
+ const loaded = await Promise.all(target.pullRequestNumbers.map(async (number) => {
1727
+ try {
1728
+ const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
1729
+ return loadedFacts ? [number, loadedFacts] : void 0;
1730
+ } catch (error) {
1731
+ if (!isGitHubNotFoundError(error)) logFailOpenFailure(args.log, "GitHub pull request data load failed", error, {
1732
+ pullRequest: number,
1733
+ repository: `${target.owner}/${target.repoName}`
1734
+ });
1735
+ return;
1736
+ }
1737
+ }));
1738
+ const pullRequestFactsByNumber = {};
1739
+ for (const entry of loaded) {
1740
+ if (!entry) continue;
1741
+ pullRequestFactsByNumber[entry[0]] = entry[1];
1742
+ }
1743
+ if (Object.keys(pullRequestFactsByNumber).length > 0) facts.pullRequestFactsByNumber = pullRequestFactsByNumber;
1744
+ } catch (error) {
1745
+ logFailOpenFailure(args.log, "GitHub check suite pull request data load failed", error, {
1746
+ checkSuiteId: target.checkSuiteId,
1747
+ repository: `${target.owner}/${target.repoName}`
1748
+ });
1749
+ }
1750
+ return facts.failingChecks || facts.allCheckSuitesPassed || facts.pullRequestFactsByNumber ? facts : void 0;
1751
+ }
1752
+ // src/webhooks/issue-update.ts
1753
+ const issueUpdateWebhookSchema = z.object({
1754
+ action: z.enum(GITHUB_ISSUE_UPDATE_CHANGES),
1755
+ assignee: z.object({ login: z.string().nullish() }).nullish(),
1756
+ changes: z.record(z.string(), z.unknown()).optional(),
1757
+ issue: z.object({
1758
+ body: z.string().optional().nullable(),
1759
+ number: z.number(),
1760
+ title: z.string().optional(),
1761
+ updated_at: z.string().optional()
1762
+ }),
1763
+ label: z.object({ name: z.string() }).nullish(),
1764
+ milestone: z.object({ title: z.string() }).nullish(),
1765
+ repository: z.object({ full_name: z.string().min(1) }),
1766
+ sender: gitHubSenderSchema.optional()
1767
+ });
1768
+ /**
1769
+ * Describe what an `issues` update action changed. `change` is trusted text:
1770
+ * GitHub logins and field names only. Label and milestone names are
1771
+ * repository-controlled text, so they stay out of `change` and go in
1772
+ * `untrustedText`. Event data also carries the lowercase label name as a
1773
+ * match value; only people with repository write access create labels.
1774
+ */
1775
+ function describeIssueUpdate(delivery) {
1776
+ const assignee = nonBlank(delivery.assignee?.login);
1777
+ switch (delivery.action) {
1778
+ case "edited": {
1779
+ const fields = ["title", "body"].filter((field) => field in (delivery.changes ?? {}));
1780
+ return { change: fields.length ? `edited (${fields.join(", ")})` : "edited" };
1781
+ }
1782
+ case "labeled":
1783
+ case "unlabeled": return {
1784
+ change: delivery.action,
1785
+ untrustedText: delivery.label ? `Label: ${delivery.label.name}` : void 0
1786
+ };
1787
+ case "assigned": return { change: assignee ? `assigned to ${assignee}` : "assigned" };
1788
+ case "unassigned": return { change: assignee ? `unassigned from ${assignee}` : "unassigned" };
1789
+ case "milestoned":
1790
+ case "demilestoned": return {
1791
+ change: delivery.action,
1792
+ untrustedText: delivery.milestone ? `Milestone: ${delivery.milestone.title}` : void 0
1793
+ };
1794
+ }
1795
+ }
1796
+ /**
1797
+ * Normalize an issue edit, label, assignee, or milestone change into
1798
+ * `issue.updated` for the issue and its repository. Return undefined when the
1799
+ * delivery is not one of these updates. Changes that the bot makes publish
1800
+ * nothing, so Junior's own issue updates do not wake its Watches.
1801
+ */
1802
+ function normalizeIssueUpdateEvents(deliveryId, body, botEmail) {
1803
+ const parsed = issueUpdateWebhookSchema.safeParse(body);
1804
+ if (!parsed.success) return void 0;
1805
+ const update = describeIssueUpdate(parsed.data);
1806
+ const { action, label, sender } = parsed.data;
1807
+ const doneBy = sender?.login;
1808
+ if (isBotLogin(doneBy, botEmail)) return [];
1809
+ const input = {
1810
+ number: parsed.data.issue.number,
1811
+ repo: parsed.data.repository.full_name
1812
+ };
1813
+ const issue = gitHubIssueResource(input);
1814
+ const untrustedText = [update.untrustedText, titleAndBodyText(parsed.data.issue)].filter((part) => part !== void 0).join("\n\n");
1815
+ return [issue, gitHubRepositoryResource(input)].map((resource) => ({
1816
+ eventKey: gitHubEventKey(deliveryId, "issue.updated"),
1817
+ eventType: "issue.updated",
1818
+ occurredAtMs: providerTime(parsed.data.issue.updated_at) ?? Date.now(),
1819
+ identifier: resource.identifier,
1820
+ trustedSummary: `${issue.label} was ${update.change}${doneBy ? ` by ${doneBy}` : ""}.`,
1821
+ ...gitHubDoneBy(doneBy),
1822
+ data: definedValues({
1823
+ repo: gitHubRepoDataSchema.parse(input.repo),
1824
+ issue: input.number,
1825
+ change: action,
1826
+ label: label?.name.toLowerCase(),
1827
+ ...gitHubSenderData(sender)
1828
+ }),
1829
+ ...untrustedText ? { untrustedText } : void 0
1830
+ }));
1831
+ }
1832
+ // src/webhooks/events.ts
1833
+ const repositorySchema = z.object({ full_name: z.string().min(1) }).passthrough();
1834
+ const deploymentSchema = z.object({
1835
+ created_at: z.string().optional(),
1836
+ environment: z.string().trim().min(1),
1837
+ id: z.number(),
1838
+ sha: z.string().regex(/^[0-9a-f]{40}$/i)
1839
+ }).passthrough();
1840
+ const deploymentWorkflowSchema = {
1841
+ workflow: z.object({
1842
+ id: z.number(),
1843
+ path: z.string().min(1)
1844
+ }).passthrough().nullish(),
1845
+ workflow_run: z.object({ id: z.number() }).passthrough().nullish()
1846
+ };
1847
+ const deploymentWebhookSchema = z.object({
1848
+ action: z.string(),
1849
+ deployment: deploymentSchema,
1850
+ repository: repositorySchema,
1851
+ ...deploymentWorkflowSchema
1852
+ }).passthrough();
1853
+ const canonicalDeploymentEventSchema = z.object({
1854
+ action: z.string(),
1855
+ commitSha: z.string().regex(/^[0-9a-f]{40}$/i),
1856
+ createdAt: z.string().optional(),
1857
+ deploymentId: z.number(),
1858
+ environment: z.string().min(1),
1859
+ repo: z.string().min(1),
1860
+ workflowId: z.number().optional(),
1861
+ workflowPath: z.string().min(1).optional(),
1862
+ workflowRunId: z.number().optional()
1863
+ }).strict();
1864
+ /** Select the canonical deployment fields shared by both webhook envelopes. */
1865
+ function canonicalDeploymentFields(data) {
1866
+ return {
1867
+ action: data.action,
1868
+ commitSha: data.deployment.sha,
1869
+ createdAt: data.deployment.created_at,
1870
+ deploymentId: data.deployment.id,
1871
+ environment: data.deployment.environment,
1872
+ repo: data.repository.full_name,
1873
+ workflowId: data.workflow?.id,
1874
+ workflowPath: data.workflow?.path,
1875
+ workflowRunId: data.workflow_run?.id
1876
+ };
1877
+ }
1878
+ /** Convert GitHub's permissive webhook envelope into routing-safe fields. */
1879
+ function parseDeploymentEvent(body) {
1880
+ const parsed = deploymentWebhookSchema.safeParse(body);
1881
+ if (!parsed.success) return void 0;
1882
+ return canonicalDeploymentEventSchema.parse(canonicalDeploymentFields(parsed.data));
1883
+ }
1884
+ /** Normalize a newly created GitHub deployment. */
1885
+ function normalizeDeploymentEvent(deliveryId, body) {
1886
+ const parsed = parseDeploymentEvent(body);
1887
+ if (!parsed || parsed.action !== "created") return [];
1888
+ const eventType = "deployment.created";
1889
+ const { label } = gitHubDeploymentSourceResource(parsed);
1890
+ return deploymentTargets(parsed).map(({ identifier }) => ({
1891
+ eventKey: gitHubEventKey(deliveryId, eventType),
1892
+ eventType,
1893
+ occurredAtMs: providerTime(parsed.createdAt) ?? Date.now(),
1894
+ identifier,
1895
+ trustedSummary: `${label} was created (deployment ${parsed.deploymentId}).`,
1896
+ data: deploymentEventData(parsed)
1897
+ }));
1898
+ }
1899
+ const deploymentStatusWebhookSchema = deploymentWebhookSchema.extend({ deployment_status: z.object({
1900
+ created_at: z.string().optional(),
1901
+ description: z.string().optional().nullable(),
1902
+ state: z.string()
1903
+ }).passthrough() });
1904
+ const canonicalDeploymentStatusEventSchema = canonicalDeploymentEventSchema.extend({
1905
+ description: z.string().optional().nullable(),
1906
+ state: z.string(),
1907
+ statusCreatedAt: z.string().optional()
1908
+ }).strict();
1909
+ /** Convert a GitHub status envelope into canonical deployment event fields. */
1910
+ function parseDeploymentStatusEvent(body) {
1911
+ const parsed = deploymentStatusWebhookSchema.safeParse(body);
1912
+ if (!parsed.success) return void 0;
1913
+ return canonicalDeploymentStatusEventSchema.parse({
1914
+ ...canonicalDeploymentFields(parsed.data),
1915
+ description: parsed.data.deployment_status.description,
1916
+ state: parsed.data.deployment_status.state,
1917
+ statusCreatedAt: parsed.data.deployment_status.created_at
1918
+ });
1919
+ }
1920
+ /** Map GitHub status vocabulary to Junior's deployment event contract. */
1921
+ function deploymentStatusEventType(state) {
1922
+ switch (state) {
1923
+ case "queued":
1924
+ case "pending":
1925
+ case "in_progress": return `deployment.${state}`;
1926
+ case "success": return "deployment.succeeded";
1927
+ case "failure": return "deployment.failed";
1928
+ case "error": return "deployment.error";
1929
+ default: return;
1930
+ }
1931
+ }
1932
+ /** Normalize a GitHub deployment status into a source event. */
1933
+ function normalizeDeploymentStatusEvent(deliveryId, body) {
1934
+ const parsed = parseDeploymentStatusEvent(body);
1935
+ if (!parsed || parsed.action !== "created") return [];
1936
+ const eventType = deploymentStatusEventType(parsed.state);
1937
+ if (!eventType) return [];
1938
+ const outcome = eventType === "deployment.succeeded" ? "succeeded" : eventType === "deployment.failed" ? "failed" : eventType === "deployment.error" ? "reported an error" : eventType === "deployment.in_progress" ? "started" : `is ${parsed.state}`;
1939
+ const terminal = eventType === "deployment.succeeded" || eventType === "deployment.failed" || eventType === "deployment.error";
1940
+ const { label } = gitHubDeploymentSourceResource(parsed);
1941
+ return deploymentTargets(parsed).map(({ completeOnTerminalEvent, identifier }) => ({
1942
+ eventKey: gitHubEventKey(deliveryId, eventType),
1943
+ eventType,
1944
+ occurredAtMs: providerTime(parsed.statusCreatedAt) ?? Date.now(),
1945
+ identifier,
1946
+ ...terminal && completeOnTerminalEvent ? { terminal: true } : void 0,
1947
+ trustedSummary: `${label} ${outcome} (deployment ${parsed.deploymentId}).`,
1948
+ data: deploymentEventData(parsed),
1949
+ untrustedText: parsed.description ?? void 0
1950
+ }));
1951
+ }
1952
+ /** Trusted data on every deployment event. */
1953
+ const deploymentEventDataSchema = z.object({
1954
+ repo: gitHubRepoDataSchema,
1955
+ commitSha: gitHubCommitShaDataSchema,
1956
+ deploymentId: z.number(),
1957
+ environment: z.string().trim().min(1).toLowerCase(),
1958
+ workflowId: z.number().optional(),
1959
+ workflowPath: z.string().min(1).optional(),
1960
+ workflowRunId: z.number().optional()
1961
+ }).strict();
1962
+ /** Build the trusted data of one deployment event. */
1963
+ function deploymentEventData(input) {
1964
+ return deploymentEventDataSchema.parse(definedValues({
1965
+ repo: input.repo,
1966
+ commitSha: input.commitSha,
1967
+ deploymentId: input.deploymentId,
1968
+ environment: input.environment,
1969
+ workflowId: input.workflowId,
1970
+ workflowPath: input.workflowPath,
1971
+ workflowRunId: input.workflowRunId
1972
+ }));
1973
+ }
1974
+ /**
1975
+ * Address one deployment through its exact environment, its commit, and its
1976
+ * repository. Only the exact target completes on a terminal status; the
1977
+ * repository target lets event automations follow every deployment.
1978
+ */
1979
+ function deploymentTargets(input) {
1980
+ return [
1981
+ {
1982
+ completeOnTerminalEvent: true,
1983
+ identifier: gitHubDeploymentSourceResource(input).identifier
1984
+ },
1985
+ {
1986
+ completeOnTerminalEvent: false,
1987
+ identifier: gitHubDeploymentSourceResource({
1988
+ commitSha: input.commitSha,
1989
+ repo: input.repo
1990
+ }).identifier
1991
+ },
1992
+ {
1993
+ completeOnTerminalEvent: false,
1994
+ identifier: gitHubRepositoryResource({ repo: input.repo }).identifier
1995
+ }
1996
+ ];
1997
+ }
1998
+ const gitHubUserSchema = z.object({
1999
+ email: z.string().nullish(),
2000
+ login: z.string().nullish()
2001
+ });
2002
+ const commentSchema = z.object({
2003
+ body: z.string(),
2004
+ id: z.number(),
2005
+ user: z.object({ login: z.string().optional() }).optional()
2006
+ });
2007
+ /** Trusted data that every comment and review event sets. */
2008
+ const commentAuthorDataSchema = z.object({
2009
+ mentionsBot: z.boolean().optional(),
2010
+ senderId: z.number().optional(),
2011
+ senderLogin: z.string().min(1).optional()
2012
+ });
2013
+ /**
2014
+ * Who wrote a comment or review, and whether its text mentions the bot.
2015
+ * `mentionsBot` is set only when the bot email is configured.
2016
+ */
2017
+ function commentAuthorData(input) {
2018
+ return {
2019
+ mentionsBot: input.botEmail ? mentionsBotLogin(input.text ?? "", input.botEmail) : void 0,
2020
+ ...gitHubSenderData(input.sender)
2021
+ };
2022
+ }
2023
+ /** The pull request values that every pull request webhook sends. */
2024
+ const pullRequestSchema = z.object({
2025
+ draft: z.boolean().optional(),
2026
+ head: z.object({ ref: z.string().nullish() }).nullish(),
2027
+ number: z.number(),
2028
+ user: gitHubUserSchema.nullish()
2029
+ });
2030
+ /**
2031
+ * Trusted data on every pull request event. The opener is the GitHub user
2032
+ * who opened the pull request, not the commenter. The pull request comment
2033
+ * webhook has no head branch.
2034
+ */
2035
+ const pullRequestEventDataSchema = commentAuthorDataSchema.extend({
2036
+ repo: gitHubRepoDataSchema,
2037
+ pullRequest: z.number(),
2038
+ headBranch: z.string().min(1).optional(),
2039
+ isDraft: z.boolean().optional(),
2040
+ openerEmail: z.string().min(1).optional(),
2041
+ openerUsername: z.string().min(1).optional(),
2042
+ commentId: z.number().optional(),
2043
+ commentKind: z.enum([
2044
+ "conversation",
2045
+ "review",
2046
+ "review_body"
2047
+ ]).optional()
2048
+ }).strict();
2049
+ /** Build the trusted data of one pull request event. */
2050
+ function pullRequestEventData(input) {
2051
+ const { pullRequest } = input;
2052
+ return pullRequestEventDataSchema.parse(definedValues({
2053
+ repo: input.repo,
2054
+ pullRequest: pullRequest.number,
2055
+ headBranch: nonBlank(pullRequest.head?.ref),
2056
+ isDraft: pullRequest.draft,
2057
+ openerEmail: nonBlank(pullRequest.user?.email),
2058
+ openerUsername: nonBlank(pullRequest.user?.login),
2059
+ ...input.comment
2060
+ }));
2061
+ }
2062
+ /** Trusted data on every issue event. */
2063
+ const issueEventDataSchema = commentAuthorDataSchema.extend({
2064
+ repo: gitHubRepoDataSchema,
2065
+ issue: z.number(),
2066
+ commentId: z.number().optional()
2067
+ }).strict();
2068
+ /** Build the trusted data of one issue event. */
2069
+ function issueEventData(input) {
2070
+ return issueEventDataSchema.parse(definedValues(input));
2071
+ }
2072
+ const issueCommentWebhookSchema = z.object({
2073
+ action: z.string(),
2074
+ comment: commentSchema,
2075
+ issue: z.object({
2076
+ draft: z.boolean().optional(),
2077
+ number: z.number(),
2078
+ pull_request: z.object({ url: z.string().min(1) }).optional(),
2079
+ user: gitHubUserSchema.nullish()
2080
+ }),
2081
+ repository: repositorySchema,
2082
+ sender: gitHubSenderSchema.optional()
2083
+ });
2084
+ /** Normalize a newly created issue or pull request comment. */
2085
+ function normalizeIssueCommentEvents(deliveryId, body, botEmail) {
2086
+ const parsed = issueCommentWebhookSchema.safeParse(body);
2087
+ if (!parsed.success || parsed.data.action !== "created") return [];
2088
+ const { comment, issue, sender } = parsed.data;
2089
+ const author = comment.user?.login;
2090
+ if (isBotLogin(author, botEmail)) return [];
2091
+ const input = {
2092
+ number: issue.number,
2093
+ repo: parsed.data.repository.full_name
2094
+ };
2095
+ const writtenBy = commentAuthorData({
2096
+ botEmail,
2097
+ sender,
2098
+ text: comment.body
2099
+ });
2100
+ if (issue.pull_request) {
2101
+ const eventType = "pull_request.comment.created";
2102
+ const resource = gitHubPullRequestResource(input);
2103
+ return pullRequestTargets({
2104
+ eventKey: gitHubEventKey(deliveryId, eventType),
2105
+ eventType,
2106
+ occurredAtMs: Date.now(),
2107
+ identifier: resource.identifier,
2108
+ trustedSummary: `${resource.label} received a comment${author ? ` from ${author}` : ""}.`,
2109
+ ...gitHubDoneBy(author),
2110
+ data: pullRequestEventData({
2111
+ comment: {
2112
+ commentId: comment.id,
2113
+ commentKind: "conversation",
2114
+ ...writtenBy
2115
+ },
2116
+ pullRequest: issue,
2117
+ repo: input.repo
2118
+ }),
2119
+ untrustedText: comment.body
2120
+ }, input.repo);
2121
+ }
2122
+ const issueResource = gitHubIssueResource(input);
2123
+ const repository = gitHubRepositoryResource(input);
2124
+ const data = issueEventData({
2125
+ repo: input.repo,
2126
+ issue: input.number,
2127
+ commentId: comment.id,
2128
+ ...writtenBy
2129
+ });
2130
+ return [issueResource, repository].map((resource) => ({
2131
+ eventKey: gitHubEventKey(deliveryId, "issue.comment.created"),
2132
+ eventType: "issue.comment.created",
2133
+ occurredAtMs: Date.now(),
2134
+ identifier: resource.identifier,
2135
+ trustedSummary: `${issueResource.label} received a comment${author ? ` from ${author}` : ""}.`,
2136
+ ...gitHubDoneBy(author),
2137
+ data,
2138
+ untrustedText: comment.body
2139
+ }));
2140
+ }
2141
+ const issueWebhookSchema = z.object({
2142
+ action: z.string(),
2143
+ issue: z.object({
2144
+ body: z.string().optional().nullable(),
2145
+ closed_at: z.string().optional().nullable(),
2146
+ created_at: z.string().optional(),
2147
+ number: z.number(),
2148
+ title: z.string().optional(),
2149
+ updated_at: z.string().optional()
2150
+ }),
2151
+ repository: repositorySchema
2152
+ });
2153
+ /** Normalize issue lifecycle changes and updates for the issue and its repository. */
2154
+ function normalizeIssueEvents(deliveryId, body, botEmail) {
2155
+ const updates = normalizeIssueUpdateEvents(deliveryId, body, botEmail);
2156
+ if (updates) return updates;
2157
+ const parsed = issueWebhookSchema.safeParse(body);
2158
+ if (!parsed.success) return [];
2159
+ const state = parsed.data.action === "opened" ? "opened" : parsed.data.action === "closed" ? "closed" : parsed.data.action === "reopened" ? "reopened" : void 0;
2160
+ if (!state) return [];
2161
+ const input = {
2162
+ number: parsed.data.issue.number,
2163
+ repo: parsed.data.repository.full_name
2164
+ };
2165
+ const issue = gitHubIssueResource(input);
2166
+ const repository = gitHubRepositoryResource(input);
2167
+ const occurredAtMs = providerTime(state === "opened" ? parsed.data.issue.created_at : state === "closed" ? parsed.data.issue.closed_at : parsed.data.issue.updated_at) ?? Date.now();
2168
+ const data = issueEventData({
2169
+ repo: input.repo,
2170
+ issue: input.number
2171
+ });
2172
+ const untrustedText = titleAndBodyText(parsed.data.issue);
2173
+ return [issue, repository].map((resource) => ({
2174
+ eventKey: gitHubEventKey(deliveryId, `issue.${state}`),
2175
+ eventType: `issue.${state}`,
2176
+ occurredAtMs,
2177
+ identifier: resource.identifier,
2178
+ trustedSummary: `${issue.label} was ${state}.`,
2179
+ data,
2180
+ ...untrustedText ? { untrustedText } : void 0
2181
+ }));
2182
+ }
2183
+ const pullRequestReviewCommentWebhookSchema = z.object({
2184
+ action: z.string(),
2185
+ comment: commentSchema,
2186
+ pull_request: pullRequestSchema,
2187
+ repository: repositorySchema,
2188
+ sender: gitHubSenderSchema.optional()
2189
+ });
2190
+ /** Normalize a newly created inline pull request review comment. */
2191
+ function normalizePullRequestReviewCommentEvent(deliveryId, body, botEmail) {
2192
+ const parsed = pullRequestReviewCommentWebhookSchema.safeParse(body);
2193
+ if (!parsed.success || parsed.data.action !== "created") return [];
2194
+ const { comment, pull_request: pullRequest, sender } = parsed.data;
2195
+ const author = comment.user?.login;
2196
+ if (isBotLogin(author, botEmail)) return [];
2197
+ const eventType = "pull_request.review_comment.created";
2198
+ const repo = parsed.data.repository.full_name;
2199
+ const resource = gitHubPullRequestResource({
2200
+ number: pullRequest.number,
2201
+ repo
2202
+ });
2203
+ return pullRequestTargets({
2204
+ eventKey: gitHubEventKey(deliveryId, eventType),
2205
+ eventType,
2206
+ occurredAtMs: Date.now(),
2207
+ identifier: resource.identifier,
2208
+ trustedSummary: `${resource.label} received an inline review comment${author ? ` from ${author}` : ""}.`,
2209
+ ...gitHubDoneBy(author),
2210
+ data: pullRequestEventData({
2211
+ comment: {
2212
+ commentId: comment.id,
2213
+ commentKind: "review",
2214
+ ...commentAuthorData({
2215
+ botEmail,
2216
+ sender,
2217
+ text: comment.body
2218
+ })
2219
+ },
2220
+ pullRequest,
2221
+ repo
2222
+ }),
2223
+ untrustedText: comment.body
2224
+ }, repo);
2225
+ }
2226
+ const pullRequestReviewWebhookSchema = z.object({
2227
+ action: z.string(),
2228
+ pull_request: pullRequestSchema,
2229
+ repository: repositorySchema,
2230
+ review: z.object({
2231
+ body: z.string().optional().nullable(),
2232
+ id: z.number().optional(),
2233
+ state: z.string(),
2234
+ user: z.object({ login: z.string().optional() }).optional()
2235
+ }),
2236
+ sender: gitHubSenderSchema.optional()
2237
+ });
2238
+ /** Normalize a submitted pull request review into its review-state event. */
2239
+ function normalizePullRequestReviewEvent(deliveryId, body, botEmail) {
2240
+ const parsed = pullRequestReviewWebhookSchema.safeParse(body);
2241
+ if (!parsed.success || parsed.data.action !== "submitted") return [];
2242
+ const { pull_request: pullRequest, review, sender } = parsed.data;
2243
+ if (isBotLogin(review.user?.login, botEmail)) return [];
2244
+ const reviewState = review.state.toUpperCase();
2245
+ const eventType = reviewState === "APPROVED" ? "pull_request.review.approved" : reviewState === "CHANGES_REQUESTED" ? "pull_request.review.changes_requested" : reviewState === "COMMENTED" ? "pull_request.review.commented" : void 0;
2246
+ if (!eventType) return [];
2247
+ const repo = parsed.data.repository.full_name;
2248
+ const resource = gitHubPullRequestResource({
2249
+ number: pullRequest.number,
2250
+ repo
2251
+ });
2252
+ const reviewer = review.user?.login;
2253
+ const event = {
2254
+ eventKey: gitHubEventKey(deliveryId, eventType),
2255
+ eventType,
2256
+ occurredAtMs: Date.now(),
2257
+ identifier: resource.identifier,
2258
+ trustedSummary: eventType === "pull_request.review.approved" ? `${resource.label} was approved${reviewer ? ` by ${reviewer}` : ""}.` : eventType === "pull_request.review.changes_requested" ? `${resource.label} received requested changes${reviewer ? ` from ${reviewer}` : ""}.` : `${resource.label} received a review comment${reviewer ? ` from ${reviewer}` : ""}.`,
2259
+ ...gitHubDoneBy(reviewer),
2260
+ data: pullRequestEventData({
2261
+ comment: {
2262
+ ...review.id !== void 0 && nonBlank(review.body) ? {
2263
+ commentId: review.id,
2264
+ commentKind: "review_body"
2265
+ } : void 0,
2266
+ ...commentAuthorData({
2267
+ botEmail,
2268
+ sender,
2269
+ text: review.body
2270
+ })
2271
+ },
2272
+ pullRequest,
2273
+ repo
2274
+ }),
2275
+ untrustedText: review.body ?? void 0
2276
+ };
2277
+ const events = pullRequestTargets(event, repo);
2278
+ if (eventType !== "pull_request.review.approved" || !nonBlank(review.body)) return events;
2279
+ return [...events, ...pullRequestTargets({
2280
+ ...event,
2281
+ eventKey: gitHubEventKey(deliveryId, "pull_request.review.commented"),
2282
+ eventType: "pull_request.review.commented"
2283
+ }, repo)];
2284
+ }
2285
+ const pullRequestWebhookSchema = z.object({
2286
+ action: z.string(),
2287
+ pull_request: pullRequestSchema.extend({
2288
+ body: z.string().optional().nullable(),
2289
+ closed_at: z.string().optional().nullable(),
2290
+ created_at: z.string().optional(),
2291
+ merged: z.boolean().optional(),
2292
+ merged_at: z.string().optional().nullable(),
2293
+ title: z.string().optional(),
2294
+ updated_at: z.string().optional()
2295
+ }),
2296
+ repository: repositorySchema
2297
+ });
2298
+ /** Normalize pull request opened, ready-for-review, and terminal lifecycle events. */
2299
+ function normalizePullRequestEvent(deliveryId, body) {
2300
+ const parsed = pullRequestWebhookSchema.safeParse(body);
2301
+ if (!parsed.success) return [];
2302
+ const { pull_request: pullRequest } = parsed.data;
2303
+ const repo = parsed.data.repository.full_name;
2304
+ const resource = gitHubPullRequestResource({
2305
+ number: pullRequest.number,
2306
+ repo
2307
+ });
2308
+ const data = pullRequestEventData({
2309
+ pullRequest,
2310
+ repo
2311
+ });
2312
+ const readyData = pullRequestEventData({
2313
+ pullRequest: {
2314
+ ...pullRequest,
2315
+ draft: false
2316
+ },
2317
+ repo
2318
+ });
2319
+ const untrustedText = titleAndBodyText(pullRequest);
2320
+ const lifecycleEvents = (event) => pullRequestTargets({
2321
+ eventKey: gitHubEventKey(deliveryId, event.eventType),
2322
+ eventType: event.eventType,
2323
+ occurredAtMs: event.occurredAtMs,
2324
+ identifier: resource.identifier,
2325
+ trustedSummary: event.trustedSummary,
2326
+ data: event.isDraft === false ? readyData : data,
2327
+ ...event.untrustedText ? { untrustedText: event.untrustedText } : void 0
2328
+ }, repo);
2329
+ if (parsed.data.action === "opened") {
2330
+ const openedAtMs = providerTime(pullRequest.created_at) ?? Date.now();
2331
+ const events = lifecycleEvents({
2332
+ eventType: "pull_request.opened",
2333
+ occurredAtMs: openedAtMs,
2334
+ trustedSummary: `${resource.label} was opened.`,
2335
+ untrustedText
2336
+ });
2337
+ if (pullRequest.draft !== true) events.push(...lifecycleEvents({
2338
+ eventType: "pull_request.ready_for_review",
2339
+ isDraft: false,
2340
+ occurredAtMs: openedAtMs,
2341
+ trustedSummary: `${resource.label} is ready for review.`,
2342
+ untrustedText
2343
+ }));
2344
+ return events;
2345
+ }
2346
+ if (parsed.data.action === "ready_for_review") return lifecycleEvents({
2347
+ eventType: "pull_request.ready_for_review",
2348
+ isDraft: false,
2349
+ occurredAtMs: providerTime(pullRequest.updated_at) ?? Date.now(),
2350
+ trustedSummary: `${resource.label} is ready for review.`,
2351
+ untrustedText
2352
+ });
2353
+ return gitHubPullRequestTerminalEvents(body);
2354
+ }
2355
+ /**
2356
+ * Build the merged or closed_unmerged events of one closed pull request.
2357
+ * The webhook and the daily reconcile both publish them. The key names the
2358
+ * close, not the webhook delivery, so a Watch gets the close once.
2359
+ */
2360
+ function gitHubPullRequestTerminalEvents(body) {
2361
+ const parsed = pullRequestWebhookSchema.safeParse(body);
2362
+ if (!parsed.success || parsed.data.action !== "closed") return [];
2363
+ const { pull_request: pullRequest } = parsed.data;
2364
+ const repo = parsed.data.repository.full_name;
2365
+ const resource = gitHubPullRequestResource({
2366
+ number: pullRequest.number,
2367
+ repo
2368
+ });
2369
+ const merged = pullRequest.merged === true;
2370
+ const eventType = merged ? "pull_request.merged" : "pull_request.closed_unmerged";
2371
+ const occurredAtMs = providerTime(merged ? pullRequest.merged_at : pullRequest.closed_at) ?? providerTime(pullRequest.updated_at) ?? Date.now();
2372
+ return pullRequestTargets({
2373
+ eventKey: merged ? `github:${resource.identifier}:${eventType}` : `github:${resource.identifier}:${eventType}:${occurredAtMs}`,
2374
+ eventType,
2375
+ occurredAtMs,
2376
+ identifier: resource.identifier,
2377
+ terminal: true,
2378
+ trustedSummary: merged ? `${resource.label} was merged.` : `${resource.label} was closed without being merged.`,
2379
+ data: pullRequestEventData({
2380
+ pullRequest,
2381
+ repo
2382
+ })
2383
+ }, repo);
2384
+ }
2385
+ const releaseWebhookSchema = z.object({
2386
+ action: z.string(),
2387
+ release: z.object({
2388
+ body: z.string().optional().nullable(),
2389
+ draft: z.boolean().optional(),
2390
+ id: z.number(),
2391
+ name: z.string().optional().nullable(),
2392
+ prerelease: z.boolean().optional(),
2393
+ published_at: z.string().optional().nullable(),
2394
+ tag_name: z.string().min(1)
2395
+ }).passthrough(),
2396
+ repository: repositorySchema
2397
+ }).passthrough();
2398
+ /** Trusted data on every release event. */
2399
+ const releaseEventDataSchema = z.object({
2400
+ repo: gitHubRepoDataSchema,
2401
+ tag: gitHubReleaseTagDataSchema
2402
+ }).strict();
2403
+ /** Address one release through both its exact tag and its repository. */
2404
+ function releaseSourceTargets(input) {
2405
+ return [{
2406
+ completeOnTerminalEvent: true,
2407
+ resource: gitHubReleaseSourceResource(input)
2408
+ }, {
2409
+ completeOnTerminalEvent: false,
2410
+ resource: gitHubReleaseSourceResource({ repo: input.repo })
2411
+ }];
2412
+ }
2413
+ /** Normalize a published GitHub release for tag and repository watches. */
2414
+ function normalizeReleaseEvent(deliveryId, body) {
2415
+ const parsed = releaseWebhookSchema.safeParse(body);
2416
+ if (!parsed.success || parsed.data.action !== "published") return [];
2417
+ if (parsed.data.release.draft) return [];
2418
+ const eventType = "release.published";
2419
+ const repo = parsed.data.repository.full_name;
2420
+ const tag = parsed.data.release.tag_name.trim();
2421
+ if (!tag) return [];
2422
+ const untrustedParts = [
2423
+ `Tag: ${tag}`,
2424
+ parsed.data.release.name?.trim() ? `Name: ${parsed.data.release.name.trim()}` : void 0,
2425
+ parsed.data.release.body?.trim() || void 0
2426
+ ].filter((part) => part !== void 0);
2427
+ const untrustedText = untrustedParts.length > 0 ? untrustedParts.join("\n\n") : void 0;
2428
+ const data = releaseEventDataSchema.parse({
2429
+ repo,
2430
+ tag
2431
+ });
2432
+ return releaseSourceTargets({
2433
+ repo,
2434
+ tag
2435
+ }).map(({ completeOnTerminalEvent, resource }) => ({
2436
+ eventKey: gitHubEventKey(deliveryId, eventType),
2437
+ eventType,
2438
+ occurredAtMs: providerTime(parsed.data.release.published_at) ?? Date.now(),
2439
+ identifier: resource.identifier,
2440
+ ...completeOnTerminalEvent ? { terminal: true } : void 0,
2441
+ trustedSummary: `${resource.label} was published (release ${parsed.data.release.id}).`,
2442
+ data,
2443
+ ...untrustedText ? { untrustedText } : void 0
2444
+ }));
2445
+ }
2446
+ /**
2447
+ * Normalize one verified GitHub delivery into conversation events.
2448
+ *
2449
+ * Comments and reviews written by the configured bot are dropped, so Junior
2450
+ * does not react to or act on its own feedback.
2451
+ */
2452
+ function normalizeGitHubEvents(args) {
2453
+ switch (args.eventName) {
2454
+ case "deployment": return normalizeDeploymentEvent(args.deliveryId, args.body);
2455
+ case "deployment_status": return normalizeDeploymentStatusEvent(args.deliveryId, args.body);
2456
+ case "pull_request": return normalizePullRequestEvent(args.deliveryId, args.body);
2457
+ case "issues": return normalizeIssueEvents(args.deliveryId, args.body, args.botEmail);
2458
+ case "pull_request_review": return normalizePullRequestReviewEvent(args.deliveryId, args.body, args.botEmail);
2459
+ case "issue_comment": return normalizeIssueCommentEvents(args.deliveryId, args.body, args.botEmail);
2460
+ case "pull_request_review_comment": return normalizePullRequestReviewCommentEvent(args.deliveryId, args.body, args.botEmail);
2461
+ case "check_suite": return normalizeCheckSuiteEvents(args.deliveryId, args.body, args.checkSuiteFacts);
2462
+ case "release": return normalizeReleaseEvent(args.deliveryId, args.body);
2463
+ default: return [];
2464
+ }
2465
+ }
2466
+ export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRequest as C, listVerifiedUserEmails as D, issueInstallationToken as E, GITHUB_REPOSITORY_EVENTS as F, GITHUB_PULL_REQUEST_IDENTIFIER as G, GITHUB_RELEASE_SUGGESTED_EVENTS as H, GITHUB_REPOSITORY_IDENTIFIER as I, gitHubPullRequestCreateWatch as J, GITHUB_PULL_REQUEST_MATCH_FIELDS as K, GITHUB_REPOSITORY_SUGGESTED_EVENTS as L, botLoginFromEmail as M, botUserIdFromEmail as N, normalizeScopeList as O, isBotLogin as P, gitHubPullRequestSubscription as Q, gitHubRepositorySubscribable as R, githubRepositoryFromUrl as S, issueGitHubCredential as T, gitHubReleaseSourceSubscribable as U, GITHUB_RELEASE_SOURCE_IDENTIFIER as V, GITHUB_PULL_REQUEST_EVENTS as W, gitHubPullRequestResource as X, gitHubPullRequestEventGuidance as Y, gitHubPullRequestSubscribable as Z, GITHUB_INSTALLATION_ID_ENV as _, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, logFailOpenFailure as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, readGrantPermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, definedValues as l, gitHubRepoDataSchema as lt, GITHUB_AUTH_TOKEN_ENV as m, normalizeGitHubEvents as n, GITHUB_DEPLOYMENT_SUGGESTED_EVENTS as nt, parseCheckSuitePublishTargets as o, GITHUB_ISSUE_MATCH_FIELDS as ot, GITHUB_APP_PRIVATE_KEY_ENV as p, GITHUB_PULL_REQUEST_SUGGESTED_EVENTS as q, checkSuitePullRequests as r, gitHubDeploymentSourceSubscribable as rt, wantsCheckSuitePassed as s, GITHUB_ISSUE_SUGGESTED_EVENTS as st, gitHubPullRequestTerminalEvents as t, GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER as tt, pullRequestTargets as u, normalizePermissions as ut, GitHubRequestError as v, isRecord as w, createPermissionCache as x, HTTP_READ_METHODS as y, GITHUB_RELEASE_EVENTS as z };