@github-tools/sdk 1.8.2 → 1.10.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 (50) hide show
  1. package/README.md +247 -78
  2. package/dist/connect/eve.d.mts +18 -7
  3. package/dist/connect/eve.d.mts.map +1 -1
  4. package/dist/connect/eve.mjs +17 -4
  5. package/dist/connect/eve.mjs.map +1 -1
  6. package/dist/connect.d.mts +31 -11
  7. package/dist/connect.d.mts.map +1 -1
  8. package/dist/connect.mjs +6 -3
  9. package/dist/connect.mjs.map +1 -1
  10. package/dist/eve-runtime-CI4dR_hI.d.mts +54 -0
  11. package/dist/eve-runtime-CI4dR_hI.d.mts.map +1 -0
  12. package/dist/eve-runtime-CIcrt7MD.mjs +674 -0
  13. package/dist/eve-runtime-CIcrt7MD.mjs.map +1 -0
  14. package/dist/eve-runtime.d.mts +4 -0
  15. package/dist/eve-runtime.mjs +3 -0
  16. package/dist/eve.d.mts +331 -112
  17. package/dist/eve.d.mts.map +1 -1
  18. package/dist/eve.mjs +356 -3
  19. package/dist/eve.mjs.map +1 -0
  20. package/dist/index-B0nL0C00.d.mts +746 -0
  21. package/dist/index-B0nL0C00.d.mts.map +1 -0
  22. package/dist/index.d.mts +2 -2
  23. package/dist/index.mjs +3 -3
  24. package/dist/src-v-LjzPpR.mjs +1371 -0
  25. package/dist/src-v-LjzPpR.mjs.map +1 -0
  26. package/dist/{token-CW8lQBND.mjs → token-DDMlEkK-.mjs} +74 -7
  27. package/dist/token-DDMlEkK-.mjs.map +1 -0
  28. package/dist/types-VW0m0Uxl.d.mts +39 -0
  29. package/dist/types-VW0m0Uxl.d.mts.map +1 -0
  30. package/dist/{types-B0mvQgJf.d.mts → types-Ygt1pw1N.d.mts} +30 -9
  31. package/dist/types-Ygt1pw1N.d.mts.map +1 -0
  32. package/dist/workflow.d.mts +7 -7
  33. package/dist/workflow.d.mts.map +1 -1
  34. package/dist/workflow.mjs +6 -4
  35. package/dist/workflow.mjs.map +1 -1
  36. package/dist/write-tools-uIVfURVp.mjs +3509 -0
  37. package/dist/write-tools-uIVfURVp.mjs.map +1 -0
  38. package/package.json +17 -13
  39. package/dist/eve-UPaHEGVi.mjs +0 -512
  40. package/dist/eve-UPaHEGVi.mjs.map +0 -1
  41. package/dist/index-Cs1Kebmt.d.mts +0 -463
  42. package/dist/index-Cs1Kebmt.d.mts.map +0 -1
  43. package/dist/src-CfzZfU82.mjs +0 -812
  44. package/dist/src-CfzZfU82.mjs.map +0 -1
  45. package/dist/token-CW8lQBND.mjs.map +0 -1
  46. package/dist/types-B0mvQgJf.d.mts.map +0 -1
  47. package/dist/types-DwHrGKWO.d.mts +0 -27
  48. package/dist/types-DwHrGKWO.d.mts.map +0 -1
  49. package/dist/write-tools-Dx9LfYlU.mjs +0 -1840
  50. package/dist/write-tools-Dx9LfYlU.mjs.map +0 -1
@@ -0,0 +1,3509 @@
1
+ import { z } from "zod";
2
+ import { Octokit } from "octokit";
3
+ //#region src/client.ts
4
+ /** @see https://docs.github.com/en/rest/about-the-rest-api/api-versions */
5
+ const GITHUB_API_VERSION = "2026-03-10";
6
+ function createOctokit(token) {
7
+ const octokit = new Octokit({ auth: token });
8
+ octokit.hook.before("request", (options) => {
9
+ options.headers = {
10
+ ...options.headers,
11
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
12
+ };
13
+ });
14
+ return octokit;
15
+ }
16
+ //#endregion
17
+ //#region src/core/sha1.ts
18
+ /** SHA-1 hex digest without Node.js `crypto` (safe in workflow bundles). */
19
+ function sha1Hex(data) {
20
+ const words = /* @__PURE__ */ new Uint32Array(80);
21
+ const bitLength = data.length * 8;
22
+ const padded = new Uint8Array(data.length + 9 + 63 >> 6 << 6);
23
+ padded.set(data);
24
+ padded[data.length] = 128;
25
+ const view = new DataView(padded.buffer);
26
+ view.setUint32(padded.length - 4, bitLength >>> 0, false);
27
+ view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296), false);
28
+ let h0 = 1732584193;
29
+ let h1 = 4023233417;
30
+ let h2 = 2562383102;
31
+ let h3 = 271733878;
32
+ let h4 = 3285377520;
33
+ for (let offset = 0; offset < padded.length; offset += 64) {
34
+ for (let j = 0; j < 16; j++) words[j] = view.getUint32(offset + j * 4, false);
35
+ for (let j = 16; j < 80; j++) words[j] = rotl(words[j - 3] ^ words[j - 8] ^ words[j - 14] ^ words[j - 16], 1);
36
+ let a = h0;
37
+ let b = h1;
38
+ let c = h2;
39
+ let d = h3;
40
+ let e = h4;
41
+ for (let j = 0; j < 80; j++) {
42
+ let f;
43
+ let k;
44
+ if (j < 20) {
45
+ f = b & c | ~b & d;
46
+ k = 1518500249;
47
+ } else if (j < 40) {
48
+ f = b ^ c ^ d;
49
+ k = 1859775393;
50
+ } else if (j < 60) {
51
+ f = b & c | b & d | c & d;
52
+ k = 2400959708;
53
+ } else {
54
+ f = b ^ c ^ d;
55
+ k = 3395469782;
56
+ }
57
+ const temp = rotl(a, 5) + f + e + k + words[j] >>> 0;
58
+ e = d;
59
+ d = c;
60
+ c = rotl(b, 30);
61
+ b = a;
62
+ a = temp;
63
+ }
64
+ h0 = h0 + a >>> 0;
65
+ h1 = h1 + b >>> 0;
66
+ h2 = h2 + c >>> 0;
67
+ h3 = h3 + d >>> 0;
68
+ h4 = h4 + e >>> 0;
69
+ }
70
+ return [
71
+ h0,
72
+ h1,
73
+ h2,
74
+ h3,
75
+ h4
76
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
77
+ }
78
+ function rotl(value, bits) {
79
+ return (value << bits | value >>> 32 - bits) >>> 0;
80
+ }
81
+ //#endregion
82
+ //#region src/core/git-blob-sha.ts
83
+ /** Compute the git blob SHA (SHA-1 of "blob {size}\\0{content}") for a given string. */
84
+ function gitBlobSha(content) {
85
+ const contentBytes = new TextEncoder().encode(content);
86
+ const header = new TextEncoder().encode(`blob ${contentBytes.length}\0`);
87
+ const payload = new Uint8Array(header.length + contentBytes.length);
88
+ payload.set(header);
89
+ payload.set(contentBytes, header.length);
90
+ return sha1Hex(payload);
91
+ }
92
+ //#endregion
93
+ //#region src/core/repository.ts
94
+ const CREATE_COMMIT_ON_BRANCH_MUTATION = `
95
+ mutation CreateCommitOnBranch($input: CreateCommitOnBranchInput!) {
96
+ createCommitOnBranch(input: $input) { commit { oid url } }
97
+ }
98
+ `;
99
+ var CreateCommitOnBranchError = class extends Error {
100
+ reason;
101
+ constructor(message, reason) {
102
+ super(message);
103
+ this.reason = reason;
104
+ this.name = "CreateCommitOnBranchError";
105
+ }
106
+ };
107
+ async function createCommitOnBranch(octokit, input) {
108
+ try {
109
+ const result = await octokit.graphql(CREATE_COMMIT_ON_BRANCH_MUTATION, { input: {
110
+ branch: {
111
+ repositoryNameWithOwner: `${input.owner}/${input.repo}`,
112
+ branchName: input.branch
113
+ },
114
+ expectedHeadOid: input.expectedHeadOid,
115
+ message: input.body ? {
116
+ headline: input.headline,
117
+ body: input.body
118
+ } : { headline: input.headline },
119
+ fileChanges: {
120
+ additions: input.additions,
121
+ deletions: input.deletions
122
+ }
123
+ } });
124
+ return {
125
+ commitSha: result.createCommitOnBranch.commit.oid,
126
+ commitUrl: result.createCommitOnBranch.commit.url
127
+ };
128
+ } catch (error) {
129
+ const err = error;
130
+ const types = new Set((err.errors ?? []).map((e) => e.type));
131
+ if (types.has("STALE_DATA")) throw new CreateCommitOnBranchError(err.message ?? "Stale data", "stale_data");
132
+ if (types.has("FORBIDDEN") || types.has("INSUFFICIENT_SCOPES") || err.status === 401 || err.status === 403) throw new CreateCommitOnBranchError(err.message ?? "Forbidden", "forbidden");
133
+ throw error;
134
+ }
135
+ }
136
+ function composeCommitMessage(message, coAuthors) {
137
+ if (!coAuthors?.length) return message;
138
+ const trailers = coAuthors.map(({ name, email }) => `Co-authored-by: ${name} <${email}>`).join("\n");
139
+ return message ? `${message}\n\n${trailers}` : trailers;
140
+ }
141
+ const getRepositoryInputSchema = z.object({
142
+ owner: z.string().describe("Repository owner (user or organization)"),
143
+ repo: z.string().describe("Repository name")
144
+ });
145
+ const getRepositoryDescription = "Get information about a GitHub repository including description, stars, forks, language, and default branch";
146
+ async function getRepositoryCore({ token, owner, repo }) {
147
+ const { data } = await createOctokit(token).rest.repos.get({
148
+ owner,
149
+ repo
150
+ });
151
+ return {
152
+ name: data.name,
153
+ fullName: data.full_name,
154
+ description: data.description,
155
+ url: data.html_url,
156
+ defaultBranch: data.default_branch,
157
+ stars: data.stargazers_count,
158
+ forks: data.forks_count,
159
+ openIssues: data.open_issues_count,
160
+ language: data.language,
161
+ private: data.private,
162
+ createdAt: data.created_at,
163
+ updatedAt: data.updated_at
164
+ };
165
+ }
166
+ const listBranchesInputSchema = z.object({
167
+ owner: z.string().describe("Repository owner"),
168
+ repo: z.string().describe("Repository name"),
169
+ perPage: z.number().optional().default(30).describe("Number of branches to return (max 100)")
170
+ });
171
+ const listBranchesDescription = "List branches in a GitHub repository";
172
+ async function listBranchesCore({ token, owner, repo, perPage }) {
173
+ const { data } = await createOctokit(token).rest.repos.listBranches({
174
+ owner,
175
+ repo,
176
+ per_page: perPage
177
+ });
178
+ return data.map((branch) => ({
179
+ name: branch.name,
180
+ sha: branch.commit.sha,
181
+ protected: branch.protected
182
+ }));
183
+ }
184
+ const getFileContentInputSchema = z.object({
185
+ owner: z.string().describe("Repository owner"),
186
+ repo: z.string().describe("Repository name"),
187
+ path: z.string().describe("Path to the file in the repository"),
188
+ ref: z.string().optional().describe("Branch, tag, or commit SHA (defaults to the default branch)"),
189
+ startLine: z.number().int().positive().optional().describe("1-based start line to return (inclusive). Use with endLine or maxLines to avoid loading large files"),
190
+ endLine: z.number().int().positive().optional().describe("1-based end line to return (inclusive). Defaults to startLine + maxLines - 1 when maxLines is set"),
191
+ maxLines: z.number().int().positive().optional().describe("Max number of lines to return from startLine (or from line 1). Prefer this over reading an entire large file")
192
+ });
193
+ const getFileContentDescription = "Get the content of a file from a GitHub repository. Prefer startLine/endLine or maxLines to read only the lines you need";
194
+ async function getFileContentCore({ token, owner, repo, path, ref, startLine, endLine, maxLines }) {
195
+ const { data } = await createOctokit(token).rest.repos.getContent({
196
+ owner,
197
+ repo,
198
+ path,
199
+ ref
200
+ });
201
+ if (Array.isArray(data)) return {
202
+ type: "directory",
203
+ entries: data.map((e) => ({
204
+ name: e.name,
205
+ type: e.type,
206
+ path: e.path
207
+ }))
208
+ };
209
+ if (data.type !== "file") return {
210
+ type: data.type,
211
+ path: data.path
212
+ };
213
+ const fullContent = Buffer.from(data.content, "base64").toString("utf-8");
214
+ const lines = fullContent.split("\n");
215
+ const totalLines = lines.length;
216
+ if (!(startLine != null || endLine != null || maxLines != null)) return {
217
+ type: "file",
218
+ path: data.path,
219
+ sha: data.sha,
220
+ size: data.size,
221
+ totalLines,
222
+ content: fullContent
223
+ };
224
+ const from = startLine ?? 1;
225
+ const to = endLine ?? (maxLines != null ? from + maxLines - 1 : totalLines);
226
+ const clampedFrom = Math.min(Math.max(from, 1), totalLines);
227
+ const clampedTo = Math.min(Math.max(to, clampedFrom), totalLines);
228
+ const slice = lines.slice(clampedFrom - 1, clampedTo);
229
+ return {
230
+ type: "file",
231
+ path: data.path,
232
+ sha: data.sha,
233
+ size: data.size,
234
+ totalLines,
235
+ startLine: clampedFrom,
236
+ endLine: clampedTo,
237
+ truncated: clampedFrom > 1 || clampedTo < totalLines,
238
+ content: slice.join("\n")
239
+ };
240
+ }
241
+ const getRepositoryTreeInputSchema = z.object({
242
+ owner: z.string().describe("Repository owner"),
243
+ repo: z.string().describe("Repository name"),
244
+ ref: z.string().optional().describe("Branch, tag, or commit SHA (defaults to the default branch)"),
245
+ recursive: z.boolean().optional().default(false).describe("Recursively list the entire tree instead of just the top level")
246
+ });
247
+ const getRepositoryTreeDescription = "List the file and directory structure of a repository at a given ref";
248
+ async function getRepositoryTreeCore({ token, owner, repo, ref, recursive }) {
249
+ const octokit = createOctokit(token);
250
+ const treeSha = ref || (await octokit.rest.repos.get({
251
+ owner,
252
+ repo
253
+ })).data.default_branch;
254
+ const { data } = await octokit.rest.git.getTree({
255
+ owner,
256
+ repo,
257
+ tree_sha: treeSha,
258
+ recursive: recursive ? "true" : void 0
259
+ });
260
+ return {
261
+ sha: data.sha,
262
+ truncated: data.truncated,
263
+ entries: data.tree.map((entry) => ({
264
+ path: entry.path,
265
+ type: entry.type,
266
+ size: entry.size,
267
+ sha: entry.sha
268
+ }))
269
+ };
270
+ }
271
+ const createBranchInputSchema = z.object({
272
+ owner: z.string().describe("Repository owner"),
273
+ repo: z.string().describe("Repository name"),
274
+ branch: z.string().describe("Name for the new branch"),
275
+ from: z.string().optional().describe("Source branch name or commit SHA to branch from (defaults to the default branch)")
276
+ });
277
+ const createBranchDescription = "Create a new branch in a GitHub repository from an existing branch or commit SHA";
278
+ /** Idempotent when the branch already exists at the target SHA. Not idempotent otherwise. */
279
+ async function createBranchCore({ token, owner, repo, branch, from }) {
280
+ const octokit = createOctokit(token);
281
+ let sha = from;
282
+ if (!sha || !sha.match(/^[0-9a-f]{40}$/i)) {
283
+ const { data: ref } = await octokit.rest.git.getRef({
284
+ owner,
285
+ repo,
286
+ ref: `heads/${from || (await octokit.rest.repos.get({
287
+ owner,
288
+ repo
289
+ })).data.default_branch}`
290
+ });
291
+ sha = ref.object.sha;
292
+ }
293
+ try {
294
+ const { data: existingRef } = await octokit.rest.git.getRef({
295
+ owner,
296
+ repo,
297
+ ref: `heads/${branch}`
298
+ });
299
+ if (existingRef.object.sha === sha) return {
300
+ ref: existingRef.ref,
301
+ sha: existingRef.object.sha,
302
+ url: existingRef.url
303
+ };
304
+ } catch {}
305
+ const { data } = await octokit.rest.git.createRef({
306
+ owner,
307
+ repo,
308
+ ref: `refs/heads/${branch}`,
309
+ sha
310
+ });
311
+ return {
312
+ ref: data.ref,
313
+ sha: data.object.sha,
314
+ url: data.url
315
+ };
316
+ }
317
+ const forkRepositoryInputSchema = z.object({
318
+ owner: z.string().describe("Repository owner to fork from"),
319
+ repo: z.string().describe("Repository name to fork"),
320
+ organization: z.string().optional().describe("Organization to fork into (omit to fork to your personal account)"),
321
+ name: z.string().optional().describe("Name for the forked repository (defaults to the original name)")
322
+ });
323
+ const forkRepositoryDescription = "Fork a GitHub repository to the authenticated user account or a specified organization";
324
+ /** Not idempotent — each call may create another fork attempt. */
325
+ async function forkRepositoryCore({ token, owner, repo, organization, name }) {
326
+ const { data } = await createOctokit(token).rest.repos.createFork({
327
+ owner,
328
+ repo,
329
+ organization,
330
+ name
331
+ });
332
+ return {
333
+ name: data.name,
334
+ fullName: data.full_name,
335
+ url: data.html_url,
336
+ cloneUrl: data.clone_url,
337
+ sshUrl: data.ssh_url,
338
+ defaultBranch: data.default_branch,
339
+ private: data.private,
340
+ parent: data.parent ? {
341
+ fullName: data.parent.full_name,
342
+ url: data.parent.html_url
343
+ } : null
344
+ };
345
+ }
346
+ const createRepositoryInputSchema = z.object({
347
+ name: z.string().describe("Repository name"),
348
+ description: z.string().optional().describe("A short description of the repository"),
349
+ isPrivate: z.boolean().optional().default(false).describe("Whether the repository is private"),
350
+ autoInit: z.boolean().optional().default(false).describe("Create an initial commit with a README"),
351
+ gitignoreTemplate: z.string().optional().describe("Gitignore template to use (e.g. \"Node\", \"Python\")"),
352
+ licenseTemplate: z.string().optional().describe("License keyword (e.g. \"mit\", \"apache-2.0\")"),
353
+ org: z.string().optional().describe("Organization to create the repository in (omit for personal repo)")
354
+ });
355
+ const createRepositoryDescription = "Create a new GitHub repository for the authenticated user or a specified organization";
356
+ /** Not idempotent — each call creates a new repository. */
357
+ async function createRepositoryCore({ token, name, description, isPrivate, autoInit, gitignoreTemplate, licenseTemplate, org }) {
358
+ const octokit = createOctokit(token);
359
+ const params = {
360
+ name,
361
+ description,
362
+ private: isPrivate,
363
+ auto_init: autoInit,
364
+ gitignore_template: gitignoreTemplate,
365
+ license_template: licenseTemplate
366
+ };
367
+ const { data } = org ? await octokit.rest.repos.createInOrg({
368
+ org,
369
+ ...params
370
+ }) : await octokit.rest.repos.createForAuthenticatedUser(params);
371
+ return {
372
+ name: data.name,
373
+ fullName: data.full_name,
374
+ description: data.description,
375
+ url: data.html_url,
376
+ cloneUrl: data.clone_url,
377
+ sshUrl: data.ssh_url,
378
+ defaultBranch: data.default_branch,
379
+ private: data.private,
380
+ createdAt: data.created_at
381
+ };
382
+ }
383
+ const createOrUpdateFileInputSchema = z.object({
384
+ owner: z.string().describe("Repository owner"),
385
+ repo: z.string().describe("Repository name"),
386
+ path: z.string().describe("Path to the file in the repository"),
387
+ message: z.string().describe("Commit message"),
388
+ content: z.string().describe("File content (plain text, will be base64-encoded automatically)"),
389
+ branch: z.string().optional().describe("Branch to commit to (defaults to the default branch)"),
390
+ sha: z.string().optional().describe("SHA of the file being replaced (required when updating an existing file)")
391
+ });
392
+ const createOrUpdateFileDescription = "Create or update a file in a GitHub repository. Provide the SHA when updating an existing file.";
393
+ /** Idempotent when updating with sha and content is unchanged. Not idempotent for new commits. */
394
+ async function createOrUpdateFileCore({ token, owner, repo, path, message, content, branch, sha, author, committer, coAuthors }) {
395
+ const octokit = createOctokit(token);
396
+ if (sha) {
397
+ const branchName = branch || (await octokit.rest.repos.get({
398
+ owner,
399
+ repo
400
+ })).data.default_branch;
401
+ try {
402
+ const { data: fileData } = await octokit.rest.repos.getContent({
403
+ owner,
404
+ repo,
405
+ path,
406
+ ref: branchName
407
+ });
408
+ if (!Array.isArray(fileData) && fileData.type === "file") {
409
+ if (Buffer.from(fileData.content, "base64").toString("utf-8") === content) return {
410
+ path: fileData.path,
411
+ sha: fileData.sha,
412
+ skipped: true,
413
+ message: "Content unchanged; no commit created"
414
+ };
415
+ }
416
+ } catch {}
417
+ }
418
+ if (!author && !committer) try {
419
+ const branchName = branch || (await octokit.rest.repos.get({
420
+ owner,
421
+ repo
422
+ })).data.default_branch;
423
+ const { data: ref } = await octokit.rest.git.getRef({
424
+ owner,
425
+ repo,
426
+ ref: `heads/${branchName}`
427
+ });
428
+ const [headline, ...rest] = composeCommitMessage(message, coAuthors).split("\n");
429
+ const body = rest.join("\n").replace(/^\n+/, "") || void 0;
430
+ const result = await createCommitOnBranch(octokit, {
431
+ owner,
432
+ repo,
433
+ branch: branchName,
434
+ expectedHeadOid: ref.object.sha,
435
+ headline,
436
+ body,
437
+ additions: [{
438
+ path,
439
+ contents: Buffer.from(content).toString("base64")
440
+ }]
441
+ });
442
+ return {
443
+ path,
444
+ sha: gitBlobSha(content),
445
+ commitSha: result.commitSha,
446
+ commitUrl: result.commitUrl
447
+ };
448
+ } catch (error) {
449
+ if (error instanceof CreateCommitOnBranchError && error.reason === "stale_data") throw error;
450
+ const msg = error instanceof Error ? error.message : String(error);
451
+ console.warn(`[github-tools] Signed commit failed, using REST API: ${msg}`);
452
+ }
453
+ const encoded = Buffer.from(content).toString("base64");
454
+ const finalMessage = composeCommitMessage(message, coAuthors);
455
+ const { data } = await octokit.rest.repos.createOrUpdateFileContents({
456
+ owner,
457
+ repo,
458
+ path,
459
+ message: finalMessage,
460
+ content: encoded,
461
+ branch,
462
+ sha,
463
+ author,
464
+ committer
465
+ });
466
+ return {
467
+ path: data.content?.path,
468
+ sha: data.content?.sha,
469
+ commitSha: data.commit.sha,
470
+ commitUrl: data.commit.html_url
471
+ };
472
+ }
473
+ //#endregion
474
+ //#region src/core/model-output.ts
475
+ const MAX_PATCH_LENGTH = 4e3;
476
+ const MAX_CONTENT_LENGTH = 2e4;
477
+ function truncateText(text, maxLength) {
478
+ if (text.length <= maxLength) return text;
479
+ return `${text.slice(0, maxLength)}\n\n[truncated: ${text.length - maxLength} more characters]`;
480
+ }
481
+ function truncatePatchFields(files) {
482
+ return files.map((file) => ({
483
+ ...file,
484
+ patch: file.patch ? truncateText(file.patch, MAX_PATCH_LENGTH) : file.patch
485
+ }));
486
+ }
487
+ function listPullRequestFilesToModelOutput({ output }) {
488
+ return {
489
+ type: "json",
490
+ value: truncatePatchFields(output)
491
+ };
492
+ }
493
+ function getCommitToModelOutput({ output }) {
494
+ const commit = output;
495
+ return {
496
+ type: "json",
497
+ value: {
498
+ ...commit,
499
+ files: commit.files ? truncatePatchFields(commit.files) : commit.files
500
+ }
501
+ };
502
+ }
503
+ function compareCommitsToModelOutput({ output }) {
504
+ const comparison = output;
505
+ return {
506
+ type: "json",
507
+ value: {
508
+ ...comparison,
509
+ files: comparison.files ? truncatePatchFields(comparison.files) : comparison.files
510
+ }
511
+ };
512
+ }
513
+ function getFileContentToModelOutput({ output }) {
514
+ const result = output;
515
+ if ("content" in result && result.content.length > MAX_CONTENT_LENGTH) return {
516
+ type: "json",
517
+ value: {
518
+ ...result,
519
+ content: truncateText(result.content, MAX_CONTENT_LENGTH)
520
+ }
521
+ };
522
+ return {
523
+ type: "json",
524
+ value: result
525
+ };
526
+ }
527
+ function getPullRequestContextToModelOutput({ output }) {
528
+ const result = output;
529
+ return {
530
+ type: "json",
531
+ value: {
532
+ ...result,
533
+ files: result.files ? truncatePatchFields(result.files) : result.files
534
+ }
535
+ };
536
+ }
537
+ //#endregion
538
+ //#region src/core/token.ts
539
+ const TOKEN_REQUIRED_ERROR = "GitHub token is required. Pass it as `token` or set the GITHUB_TOKEN environment variable.";
540
+ /**
541
+ * Normalizes a token string, async token provider, or `process.env.GITHUB_TOKEN`
542
+ * into a `() => Promise<string>` resolver.
543
+ *
544
+ * Throws immediately for static inputs when no token is available. Provider
545
+ * functions are validated lazily, each time the resolver is invoked.
546
+ */
547
+ function createGithubTokenResolver(token) {
548
+ if (typeof token === "function") return async () => {
549
+ const resolvedToken = await token();
550
+ if (!resolvedToken) throw new Error(TOKEN_REQUIRED_ERROR);
551
+ return resolvedToken;
552
+ };
553
+ const resolvedToken = token || process.env.GITHUB_TOKEN;
554
+ if (!resolvedToken) throw new Error(TOKEN_REQUIRED_ERROR);
555
+ return async () => resolvedToken;
556
+ }
557
+ /** Resolves a {@link GithubTokenInput} to a token string. */
558
+ function resolveGithubToken(token) {
559
+ return createGithubTokenResolver(token)();
560
+ }
561
+ /**
562
+ * Controls how much text is returned for bodies/notes.
563
+ * - `summary` — truncate long bodies (~500 chars) to save tokens (default)
564
+ * - `full` — return the complete body
565
+ */
566
+ const detailSchema = z.enum(["summary", "full"]).optional().default("summary").describe("summary truncates long bodies (~500 chars) to save tokens; full returns the complete body");
567
+ /**
568
+ * Truncate a body/notes string when `detail` is `summary`.
569
+ * Returns the original value when `full`, null/undefined, or already short.
570
+ */
571
+ function applyDetailBody(body, detail, maxLength = 500) {
572
+ if (detail === "full" || body == null || body.length <= maxLength) return body;
573
+ return `${body.slice(0, maxLength)}\n\n[truncated: ${body.length - maxLength} more characters]`;
574
+ }
575
+ //#endregion
576
+ //#region src/core/pagination.ts
577
+ const maxPagesSchema = z.number().int().positive().max(20).optional().describe("Automatically fetch and combine up to this many pages on top of perPage. Omit to fetch a single page.");
578
+ /**
579
+ * Fetches a single page (`startPage`, default 1) by default. When `maxPages`
580
+ * is set, fetches pages sequentially starting at `startPage` and stops early
581
+ * once a page returns fewer than `perPage` items (the last page).
582
+ */
583
+ async function fetchAllPages(fetchPage, perPage, maxPages, startPage = 1) {
584
+ if (!maxPages || maxPages <= 1) return fetchPage(startPage);
585
+ const results = [];
586
+ for (let i = 0; i < maxPages; i++) {
587
+ const items = await fetchPage(startPage + i);
588
+ results.push(...items);
589
+ if (items.length < perPage) break;
590
+ }
591
+ return results;
592
+ }
593
+ //#endregion
594
+ //#region src/core/pull-requests.ts
595
+ const listPullRequestsInputSchema = z.object({
596
+ owner: z.string().describe("Repository owner"),
597
+ repo: z.string().describe("Repository name"),
598
+ state: z.enum([
599
+ "open",
600
+ "closed",
601
+ "all"
602
+ ]).optional().default("open").describe("Filter by state"),
603
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
604
+ maxPages: maxPagesSchema
605
+ });
606
+ const listPullRequestsDescription = "List pull requests for a GitHub repository";
607
+ async function listPullRequestsCore({ token, owner, repo, state, perPage, maxPages }) {
608
+ const octokit = createOctokit(token);
609
+ return (await fetchAllPages(async (page) => {
610
+ const { data } = await octokit.rest.pulls.list({
611
+ owner,
612
+ repo,
613
+ state,
614
+ per_page: perPage,
615
+ page
616
+ });
617
+ return data;
618
+ }, perPage, maxPages)).map((pr) => ({
619
+ number: pr.number,
620
+ title: pr.title,
621
+ state: pr.state,
622
+ url: pr.html_url,
623
+ author: pr.user?.login,
624
+ branch: pr.head.ref,
625
+ base: pr.base.ref,
626
+ draft: pr.draft,
627
+ createdAt: pr.created_at,
628
+ updatedAt: pr.updated_at
629
+ }));
630
+ }
631
+ const getPullRequestInputSchema = z.object({
632
+ owner: z.string().describe("Repository owner"),
633
+ repo: z.string().describe("Repository name"),
634
+ pullNumber: z.number().describe("Pull request number"),
635
+ detail: detailSchema
636
+ });
637
+ const getPullRequestDescription = "Get detailed information about a specific pull request. Body is truncated by default (detail: summary) — set detail full for the complete description";
638
+ async function getPullRequestCore({ token, owner, repo, pullNumber, detail = "summary" }) {
639
+ const { data } = await createOctokit(token).rest.pulls.get({
640
+ owner,
641
+ repo,
642
+ pull_number: pullNumber
643
+ });
644
+ return {
645
+ number: data.number,
646
+ title: data.title,
647
+ body: applyDetailBody(data.body, detail),
648
+ state: data.state,
649
+ url: data.html_url,
650
+ author: data.user?.login,
651
+ branch: data.head.ref,
652
+ headSha: data.head.sha,
653
+ base: data.base.ref,
654
+ draft: data.draft,
655
+ merged: data.merged,
656
+ mergeable: data.mergeable,
657
+ additions: data.additions,
658
+ deletions: data.deletions,
659
+ changedFiles: data.changed_files,
660
+ createdAt: data.created_at,
661
+ updatedAt: data.updated_at,
662
+ mergedAt: data.merged_at
663
+ };
664
+ }
665
+ const createPullRequestInputSchema = z.object({
666
+ owner: z.string().describe("Repository owner"),
667
+ repo: z.string().describe("Repository name"),
668
+ title: z.string().describe("Pull request title"),
669
+ body: z.string().optional().describe("Pull request description (supports Markdown)"),
670
+ head: z.string().describe("Branch containing the changes (format: branch or username:branch)"),
671
+ base: z.string().describe("Branch to merge into"),
672
+ draft: z.boolean().optional().default(false).describe("Create as draft pull request")
673
+ });
674
+ const createPullRequestDescription = "Create a new pull request in a GitHub repository";
675
+ /** Not idempotent — each call creates a new pull request. */
676
+ async function createPullRequestCore({ token, owner, repo, title, body, head, base, draft }) {
677
+ const { data } = await createOctokit(token).rest.pulls.create({
678
+ owner,
679
+ repo,
680
+ title,
681
+ body,
682
+ head,
683
+ base,
684
+ draft
685
+ });
686
+ return {
687
+ number: data.number,
688
+ title: data.title,
689
+ url: data.html_url,
690
+ state: data.state,
691
+ draft: data.draft,
692
+ branch: data.head.ref,
693
+ base: data.base.ref
694
+ };
695
+ }
696
+ const MARK_READY_FOR_REVIEW_MUTATION = `
697
+ mutation($pullRequestId: ID!) {
698
+ markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) {
699
+ pullRequest { id }
700
+ }
701
+ }
702
+ `;
703
+ const CONVERT_TO_DRAFT_MUTATION = `
704
+ mutation($pullRequestId: ID!) {
705
+ convertPullRequestToDraft(input: { pullRequestId: $pullRequestId }) {
706
+ pullRequest { id }
707
+ }
708
+ }
709
+ `;
710
+ const updatePullRequestInputSchema = z.object({
711
+ owner: z.string().describe("Repository owner"),
712
+ repo: z.string().describe("Repository name"),
713
+ pullNumber: z.number().describe("Pull request number"),
714
+ title: z.string().optional().describe("New pull request title"),
715
+ body: z.string().optional().describe("New pull request description (supports Markdown)"),
716
+ state: z.enum(["open", "closed"]).optional().describe("Open or close the pull request"),
717
+ base: z.string().optional().describe("Change the base branch to merge into"),
718
+ draft: z.boolean().optional().describe("Convert to draft (true) or mark as ready for review (false)")
719
+ });
720
+ const updatePullRequestDescription = "Update a pull request — title, body, state, base branch, or draft status. Draft toggling uses the GitHub GraphQL API since the REST update endpoint does not support it";
721
+ /** Not idempotent — each call applies a new revision. */
722
+ async function updatePullRequestCore({ token, owner, repo, pullNumber, title, body, state, base, draft }) {
723
+ const octokit = createOctokit(token);
724
+ const { data } = await octokit.rest.pulls.update({
725
+ owner,
726
+ repo,
727
+ pull_number: pullNumber,
728
+ title,
729
+ body,
730
+ state,
731
+ base
732
+ });
733
+ if (draft !== void 0 && draft !== data.draft) await octokit.graphql(draft ? CONVERT_TO_DRAFT_MUTATION : MARK_READY_FOR_REVIEW_MUTATION, { pullRequestId: data.node_id });
734
+ return {
735
+ number: data.number,
736
+ title: data.title,
737
+ state: data.state,
738
+ draft: draft ?? data.draft,
739
+ url: data.html_url,
740
+ base: data.base.ref,
741
+ updatedAt: data.updated_at
742
+ };
743
+ }
744
+ const mergePullRequestInputSchema = z.object({
745
+ owner: z.string().describe("Repository owner"),
746
+ repo: z.string().describe("Repository name"),
747
+ pullNumber: z.number().describe("Pull request number"),
748
+ commitTitle: z.string().optional().describe("Title for the automatic merge commit"),
749
+ commitMessage: z.string().optional().describe("Extra detail to append to automatic commit message"),
750
+ mergeMethod: z.enum([
751
+ "merge",
752
+ "squash",
753
+ "rebase"
754
+ ]).optional().default("merge").describe("Merge strategy")
755
+ });
756
+ const mergePullRequestDescription = "Merge a pull request";
757
+ /** Not idempotent — merging an already-merged PR returns an error from GitHub. */
758
+ async function mergePullRequestCore({ token, owner, repo, pullNumber, commitTitle, commitMessage, mergeMethod, coAuthors }) {
759
+ const octokit = createOctokit(token);
760
+ const finalMessage = composeCommitMessage(commitMessage ?? "", coAuthors) || void 0;
761
+ const { data } = await octokit.rest.pulls.merge({
762
+ owner,
763
+ repo,
764
+ pull_number: pullNumber,
765
+ commit_title: commitTitle,
766
+ commit_message: finalMessage,
767
+ merge_method: mergeMethod
768
+ });
769
+ return {
770
+ merged: data.merged,
771
+ message: data.message,
772
+ sha: data.sha
773
+ };
774
+ }
775
+ const addPullRequestCommentInputSchema = z.object({
776
+ owner: z.string().describe("Repository owner"),
777
+ repo: z.string().describe("Repository name"),
778
+ pullNumber: z.number().describe("Pull request number"),
779
+ body: z.string().describe("Comment text (supports Markdown)")
780
+ });
781
+ const addPullRequestCommentDescription = "Add a comment to a pull request";
782
+ /** Not idempotent — each call adds another comment. */
783
+ async function addPullRequestCommentCore({ token, owner, repo, pullNumber, body }) {
784
+ const { data } = await createOctokit(token).rest.issues.createComment({
785
+ owner,
786
+ repo,
787
+ issue_number: pullNumber,
788
+ body
789
+ });
790
+ return {
791
+ id: data.id,
792
+ url: data.html_url,
793
+ body: data.body,
794
+ author: data.user?.login,
795
+ createdAt: data.created_at
796
+ };
797
+ }
798
+ const updatePullRequestCommentInputSchema = z.object({
799
+ owner: z.string().describe("Repository owner"),
800
+ repo: z.string().describe("Repository name"),
801
+ commentId: z.number().describe("Comment ID (from the comment returned by addPullRequestComment)"),
802
+ body: z.string().describe("New comment text (supports Markdown)")
803
+ });
804
+ const updatePullRequestCommentDescription = "Update the body of a comment on a pull request";
805
+ /** Not idempotent — each call applies a new revision. */
806
+ async function updatePullRequestCommentCore({ token, owner, repo, commentId, body }) {
807
+ const { data } = await createOctokit(token).rest.issues.updateComment({
808
+ owner,
809
+ repo,
810
+ comment_id: commentId,
811
+ body
812
+ });
813
+ return {
814
+ id: data.id,
815
+ url: data.html_url,
816
+ body: data.body,
817
+ updatedAt: data.updated_at
818
+ };
819
+ }
820
+ const deletePullRequestCommentInputSchema = z.object({
821
+ owner: z.string().describe("Repository owner"),
822
+ repo: z.string().describe("Repository name"),
823
+ commentId: z.number().describe("Comment ID to delete")
824
+ });
825
+ const deletePullRequestCommentDescription = "Delete a comment from a pull request permanently";
826
+ /** Not idempotent — deleting an already-deleted comment returns 404 from GitHub. */
827
+ async function deletePullRequestCommentCore({ token, owner, repo, commentId }) {
828
+ await createOctokit(token).rest.issues.deleteComment({
829
+ owner,
830
+ repo,
831
+ comment_id: commentId
832
+ });
833
+ return {
834
+ deleted: true,
835
+ commentId
836
+ };
837
+ }
838
+ const listPullRequestFilesInputSchema = z.object({
839
+ owner: z.string().describe("Repository owner"),
840
+ repo: z.string().describe("Repository name"),
841
+ pullNumber: z.number().describe("Pull request number"),
842
+ includePatch: z.boolean().optional().default(false).describe("Include diff patches (token-heavy). Prefer false for an overview, then set true with filenames to fetch specific diffs"),
843
+ filenames: z.array(z.string()).optional().describe("If set, only return these file paths (useful with includePatch: true for targeted diffs)"),
844
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
845
+ page: z.number().optional().default(1).describe("Page number for pagination")
846
+ });
847
+ const listPullRequestFilesDescription = "List files changed in a pull request with status and stats. Patches are omitted by default — set includePatch true (optionally with filenames) to fetch diffs";
848
+ async function listPullRequestFilesCore({ token, owner, repo, pullNumber, includePatch, filenames, perPage, page }) {
849
+ const { data } = await createOctokit(token).rest.pulls.listFiles({
850
+ owner,
851
+ repo,
852
+ pull_number: pullNumber,
853
+ per_page: perPage,
854
+ page
855
+ });
856
+ const filenameSet = filenames?.length ? new Set(filenames) : null;
857
+ return data.filter((file) => !filenameSet || filenameSet.has(file.filename)).map((file) => ({
858
+ filename: file.filename,
859
+ status: file.status,
860
+ additions: file.additions,
861
+ deletions: file.deletions,
862
+ changes: file.changes,
863
+ ...includePatch && file.patch != null ? { patch: file.patch } : {}
864
+ }));
865
+ }
866
+ const listPullRequestReviewsInputSchema = z.object({
867
+ owner: z.string().describe("Repository owner"),
868
+ repo: z.string().describe("Repository name"),
869
+ pullNumber: z.number().describe("Pull request number"),
870
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
871
+ page: z.number().optional().default(1).describe("Page number for pagination")
872
+ });
873
+ const listPullRequestReviewsDescription = "List reviews on a pull request (approvals, change requests, and comments)";
874
+ async function listPullRequestReviewsCore({ token, owner, repo, pullNumber, perPage, page }) {
875
+ const { data } = await createOctokit(token).rest.pulls.listReviews({
876
+ owner,
877
+ repo,
878
+ pull_number: pullNumber,
879
+ per_page: perPage,
880
+ page
881
+ });
882
+ return data.map((review) => ({
883
+ id: review.id,
884
+ state: review.state,
885
+ body: review.body,
886
+ author: review.user?.login,
887
+ url: review.html_url,
888
+ submittedAt: review.submitted_at
889
+ }));
890
+ }
891
+ const createPullRequestReviewInputSchema = z.object({
892
+ owner: z.string().describe("Repository owner"),
893
+ repo: z.string().describe("Repository name"),
894
+ pullNumber: z.number().describe("Pull request number"),
895
+ body: z.string().optional().describe("Review body text (supports Markdown)"),
896
+ event: z.enum([
897
+ "APPROVE",
898
+ "REQUEST_CHANGES",
899
+ "COMMENT"
900
+ ]).describe("Review action: approve, request changes, or comment"),
901
+ comments: z.array(z.object({
902
+ path: z.string().describe("File path relative to the repository root"),
903
+ body: z.string().describe("Inline comment text"),
904
+ line: z.number().optional().describe("Line number in the file to comment on"),
905
+ side: z.enum(["LEFT", "RIGHT"]).optional().describe("Which side of the diff to comment on (LEFT = base, RIGHT = head)")
906
+ })).optional().describe("Inline review comments on specific files and lines")
907
+ });
908
+ const createPullRequestReviewDescription = "Submit a pull request review — approve, request changes, or comment with optional inline comments on specific lines";
909
+ /** Not idempotent — each call submits a new review. */
910
+ async function createPullRequestReviewCore({ token, owner, repo, pullNumber, body, event, comments }) {
911
+ const { data } = await createOctokit(token).rest.pulls.createReview({
912
+ owner,
913
+ repo,
914
+ pull_number: pullNumber,
915
+ body,
916
+ event,
917
+ comments
918
+ });
919
+ return {
920
+ id: data.id,
921
+ state: data.state,
922
+ body: data.body,
923
+ url: data.html_url,
924
+ author: data.user?.login,
925
+ submittedAt: data.submitted_at
926
+ };
927
+ }
928
+ const requestReviewersInputSchema = z.object({
929
+ owner: z.string().describe("Repository owner"),
930
+ repo: z.string().describe("Repository name"),
931
+ pullNumber: z.number().describe("Pull request number"),
932
+ reviewers: z.array(z.string()).optional().describe("GitHub usernames to request a review from"),
933
+ teamReviewers: z.array(z.string()).optional().describe("Team slugs to request a review from")
934
+ });
935
+ const requestReviewersDescription = "Request reviews from users or teams on a pull request";
936
+ /** Not idempotent — re-requesting an existing reviewer is a no-op on GitHub but still mutates. */
937
+ async function requestReviewersCore({ token, owner, repo, pullNumber, reviewers, teamReviewers }) {
938
+ const { data } = await createOctokit(token).rest.pulls.requestReviewers({
939
+ owner,
940
+ repo,
941
+ pull_number: pullNumber,
942
+ reviewers,
943
+ team_reviewers: teamReviewers
944
+ });
945
+ return {
946
+ number: data.number,
947
+ url: data.html_url,
948
+ requestedReviewers: data.requested_reviewers?.map((r) => r.login),
949
+ requestedTeams: data.requested_teams?.map((t) => t.slug)
950
+ };
951
+ }
952
+ //#endregion
953
+ //#region src/core/issues.ts
954
+ const listIssuesInputSchema = z.object({
955
+ owner: z.string().describe("Repository owner"),
956
+ repo: z.string().describe("Repository name"),
957
+ state: z.enum([
958
+ "open",
959
+ "closed",
960
+ "all"
961
+ ]).optional().default("open").describe("Filter by state"),
962
+ labels: z.string().optional().describe("Comma-separated list of label names to filter by"),
963
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
964
+ maxPages: maxPagesSchema
965
+ });
966
+ const listIssuesDescription = "List issues for a GitHub repository (excludes pull requests)";
967
+ async function listIssuesCore({ token, owner, repo, state, labels, perPage, maxPages }) {
968
+ const octokit = createOctokit(token);
969
+ return (await fetchAllPages(async (page) => {
970
+ const { data } = await octokit.rest.issues.listForRepo({
971
+ owner,
972
+ repo,
973
+ state,
974
+ labels,
975
+ per_page: perPage,
976
+ page
977
+ });
978
+ return data;
979
+ }, perPage, maxPages)).filter((issue) => !issue.pull_request).map((issue) => ({
980
+ number: issue.number,
981
+ title: issue.title,
982
+ state: issue.state,
983
+ url: issue.html_url,
984
+ author: issue.user?.login,
985
+ labels: issue.labels.map((l) => typeof l === "string" ? l : l.name),
986
+ createdAt: issue.created_at,
987
+ updatedAt: issue.updated_at
988
+ }));
989
+ }
990
+ const getIssueInputSchema = z.object({
991
+ owner: z.string().describe("Repository owner"),
992
+ repo: z.string().describe("Repository name"),
993
+ issueNumber: z.number().describe("Issue number"),
994
+ detail: detailSchema
995
+ });
996
+ const getIssueDescription = "Get detailed information about a specific issue. Body is truncated by default (detail: summary) — set detail full for the complete description";
997
+ async function getIssueCore({ token, owner, repo, issueNumber, detail = "summary" }) {
998
+ const { data } = await createOctokit(token).rest.issues.get({
999
+ owner,
1000
+ repo,
1001
+ issue_number: issueNumber
1002
+ });
1003
+ return {
1004
+ number: data.number,
1005
+ title: data.title,
1006
+ body: applyDetailBody(data.body, detail),
1007
+ state: data.state,
1008
+ url: data.html_url,
1009
+ author: data.user?.login,
1010
+ assignees: data.assignees?.map((a) => a.login),
1011
+ labels: data.labels.map((l) => typeof l === "string" ? l : l.name),
1012
+ comments: data.comments,
1013
+ createdAt: data.created_at,
1014
+ updatedAt: data.updated_at,
1015
+ closedAt: data.closed_at
1016
+ };
1017
+ }
1018
+ z.object({
1019
+ owner: z.string().describe("Repository owner"),
1020
+ repo: z.string().describe("Repository name"),
1021
+ issueNumber: z.number().describe("Issue number"),
1022
+ perPage: z.number().optional().default(30).describe("Number of comments to return (max 100)"),
1023
+ page: z.number().optional().default(1).describe("Page number for pagination"),
1024
+ detail: detailSchema
1025
+ });
1026
+ async function listIssueCommentsCore({ token, owner, repo, issueNumber, perPage, page, detail = "summary" }) {
1027
+ const { data } = await createOctokit(token).rest.issues.listComments({
1028
+ owner,
1029
+ repo,
1030
+ issue_number: issueNumber,
1031
+ per_page: perPage,
1032
+ page
1033
+ });
1034
+ return data.map((comment) => ({
1035
+ id: comment.id,
1036
+ url: comment.html_url,
1037
+ body: applyDetailBody(comment.body, detail),
1038
+ author: comment.user?.login,
1039
+ createdAt: comment.created_at,
1040
+ updatedAt: comment.updated_at
1041
+ }));
1042
+ }
1043
+ const createIssueInputSchema = z.object({
1044
+ owner: z.string().describe("Repository owner"),
1045
+ repo: z.string().describe("Repository name"),
1046
+ title: z.string().describe("Issue title"),
1047
+ body: z.string().optional().describe("Issue description (supports Markdown)"),
1048
+ labels: z.array(z.string()).optional().describe("Labels to apply to the issue"),
1049
+ assignees: z.array(z.string()).optional().describe("GitHub usernames to assign to the issue")
1050
+ });
1051
+ const createIssueDescription = "Create a new issue in a GitHub repository";
1052
+ /** Not idempotent — each call creates a new issue. */
1053
+ async function createIssueCore({ token, owner, repo, title, body, labels, assignees }) {
1054
+ const { data } = await createOctokit(token).rest.issues.create({
1055
+ owner,
1056
+ repo,
1057
+ title,
1058
+ body,
1059
+ labels,
1060
+ assignees
1061
+ });
1062
+ return {
1063
+ number: data.number,
1064
+ title: data.title,
1065
+ url: data.html_url,
1066
+ state: data.state,
1067
+ labels: data.labels.map((l) => typeof l === "string" ? l : l.name)
1068
+ };
1069
+ }
1070
+ const addIssueCommentInputSchema = z.object({
1071
+ owner: z.string().describe("Repository owner"),
1072
+ repo: z.string().describe("Repository name"),
1073
+ issueNumber: z.number().describe("Issue number"),
1074
+ body: z.string().describe("Comment text (supports Markdown)")
1075
+ });
1076
+ const addIssueCommentDescription = "Add a comment to a GitHub issue";
1077
+ /** Not idempotent — each call adds another comment. */
1078
+ async function addIssueCommentCore({ token, owner, repo, issueNumber, body }) {
1079
+ const { data } = await createOctokit(token).rest.issues.createComment({
1080
+ owner,
1081
+ repo,
1082
+ issue_number: issueNumber,
1083
+ body
1084
+ });
1085
+ return {
1086
+ id: data.id,
1087
+ url: data.html_url,
1088
+ body: data.body,
1089
+ author: data.user?.login,
1090
+ createdAt: data.created_at
1091
+ };
1092
+ }
1093
+ const closeIssueInputSchema = z.object({
1094
+ owner: z.string().describe("Repository owner"),
1095
+ repo: z.string().describe("Repository name"),
1096
+ issueNumber: z.number().describe("Issue number to close"),
1097
+ stateReason: z.enum(["completed", "not_planned"]).optional().default("completed").describe("Reason for closing")
1098
+ });
1099
+ const closeIssueDescription = "Close an open GitHub issue";
1100
+ /** Idempotent when the issue is already closed. */
1101
+ async function closeIssueCore({ token, owner, repo, issueNumber, stateReason }) {
1102
+ const octokit = createOctokit(token);
1103
+ const { data: existing } = await octokit.rest.issues.get({
1104
+ owner,
1105
+ repo,
1106
+ issue_number: issueNumber
1107
+ });
1108
+ if (existing.state === "closed") return {
1109
+ number: existing.number,
1110
+ title: existing.title,
1111
+ state: existing.state,
1112
+ url: existing.html_url,
1113
+ closedAt: existing.closed_at
1114
+ };
1115
+ const { data } = await octokit.rest.issues.update({
1116
+ owner,
1117
+ repo,
1118
+ issue_number: issueNumber,
1119
+ state: "closed",
1120
+ state_reason: stateReason
1121
+ });
1122
+ return {
1123
+ number: data.number,
1124
+ title: data.title,
1125
+ state: data.state,
1126
+ url: data.html_url,
1127
+ closedAt: data.closed_at
1128
+ };
1129
+ }
1130
+ const updateIssueInputSchema = z.object({
1131
+ owner: z.string().describe("Repository owner"),
1132
+ repo: z.string().describe("Repository name"),
1133
+ issueNumber: z.number().describe("Issue number"),
1134
+ title: z.string().optional().describe("New issue title"),
1135
+ body: z.string().optional().describe("New issue description (supports Markdown)"),
1136
+ state: z.enum(["open", "closed"]).optional().describe("Open or close the issue — set open to reopen a closed issue, closed to close it"),
1137
+ stateReason: z.enum([
1138
+ "completed",
1139
+ "not_planned",
1140
+ "reopened"
1141
+ ]).optional().describe("Reason for the state change (ignored unless state changes)"),
1142
+ labels: z.array(z.string()).optional().describe("Labels to set on the issue — replaces the existing set"),
1143
+ milestone: z.number().nullable().optional().describe("Milestone number to associate, or null to remove the milestone"),
1144
+ assignees: z.array(z.string()).optional().describe("GitHub usernames to set as assignees — replaces the existing set")
1145
+ });
1146
+ const updateIssueDescription = "Update a GitHub issue — title, body, labels, milestone, or assignees. Set state open to reopen a closed issue, or closed to close it";
1147
+ /** Not idempotent — each call applies a new revision. */
1148
+ async function updateIssueCore({ token, owner, repo, issueNumber, title, body, state, stateReason, labels, milestone, assignees }) {
1149
+ const { data } = await createOctokit(token).rest.issues.update({
1150
+ owner,
1151
+ repo,
1152
+ issue_number: issueNumber,
1153
+ title,
1154
+ body,
1155
+ state,
1156
+ state_reason: stateReason,
1157
+ labels,
1158
+ milestone,
1159
+ assignees
1160
+ });
1161
+ return {
1162
+ number: data.number,
1163
+ title: data.title,
1164
+ state: data.state,
1165
+ url: data.html_url,
1166
+ labels: data.labels.map((l) => typeof l === "string" ? l : l.name),
1167
+ assignees: data.assignees?.map((a) => a.login),
1168
+ milestone: data.milestone?.number ?? null,
1169
+ closedAt: data.closed_at,
1170
+ updatedAt: data.updated_at
1171
+ };
1172
+ }
1173
+ const updateIssueCommentInputSchema = z.object({
1174
+ owner: z.string().describe("Repository owner"),
1175
+ repo: z.string().describe("Repository name"),
1176
+ commentId: z.number().describe("Comment ID (from listIssueComments)"),
1177
+ body: z.string().describe("New comment text (supports Markdown)")
1178
+ });
1179
+ const updateIssueCommentDescription = "Update the body of a comment on a GitHub issue";
1180
+ /** Not idempotent — each call applies a new revision. */
1181
+ async function updateIssueCommentCore({ token, owner, repo, commentId, body }) {
1182
+ const { data } = await createOctokit(token).rest.issues.updateComment({
1183
+ owner,
1184
+ repo,
1185
+ comment_id: commentId,
1186
+ body
1187
+ });
1188
+ return {
1189
+ id: data.id,
1190
+ url: data.html_url,
1191
+ body: data.body,
1192
+ updatedAt: data.updated_at
1193
+ };
1194
+ }
1195
+ const deleteIssueCommentInputSchema = z.object({
1196
+ owner: z.string().describe("Repository owner"),
1197
+ repo: z.string().describe("Repository name"),
1198
+ commentId: z.number().describe("Comment ID to delete")
1199
+ });
1200
+ const deleteIssueCommentDescription = "Delete a comment from a GitHub issue permanently";
1201
+ /** Not idempotent — deleting an already-deleted comment returns 404 from GitHub. */
1202
+ async function deleteIssueCommentCore({ token, owner, repo, commentId }) {
1203
+ await createOctokit(token).rest.issues.deleteComment({
1204
+ owner,
1205
+ repo,
1206
+ comment_id: commentId
1207
+ });
1208
+ return {
1209
+ deleted: true,
1210
+ commentId
1211
+ };
1212
+ }
1213
+ const listLabelsInputSchema = z.object({
1214
+ owner: z.string().describe("Repository owner"),
1215
+ repo: z.string().describe("Repository name"),
1216
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
1217
+ page: z.number().optional().default(1).describe("Page number for pagination")
1218
+ });
1219
+ const listLabelsDescription = "List labels available in a GitHub repository";
1220
+ async function listLabelsCore({ token, owner, repo, perPage, page }) {
1221
+ const { data } = await createOctokit(token).rest.issues.listLabelsForRepo({
1222
+ owner,
1223
+ repo,
1224
+ per_page: perPage,
1225
+ page
1226
+ });
1227
+ return data.map((label) => ({
1228
+ name: label.name,
1229
+ color: label.color,
1230
+ description: label.description
1231
+ }));
1232
+ }
1233
+ const addLabelsInputSchema = z.object({
1234
+ owner: z.string().describe("Repository owner"),
1235
+ repo: z.string().describe("Repository name"),
1236
+ issueNumber: z.number().describe("Issue or pull request number"),
1237
+ labels: z.array(z.string()).describe("Label names to add")
1238
+ });
1239
+ const addLabelsDescription = "Add labels to an issue or pull request";
1240
+ /** Not idempotent — re-adding labels is a no-op on GitHub but still mutates. */
1241
+ async function addLabelsCore({ token, owner, repo, issueNumber, labels }) {
1242
+ const { data } = await createOctokit(token).rest.issues.addLabels({
1243
+ owner,
1244
+ repo,
1245
+ issue_number: issueNumber,
1246
+ labels
1247
+ });
1248
+ return data.map((label) => ({
1249
+ name: label.name,
1250
+ color: label.color,
1251
+ description: label.description
1252
+ }));
1253
+ }
1254
+ const removeLabelInputSchema = z.object({
1255
+ owner: z.string().describe("Repository owner"),
1256
+ repo: z.string().describe("Repository name"),
1257
+ issueNumber: z.number().describe("Issue or pull request number"),
1258
+ label: z.string().describe("Label name to remove")
1259
+ });
1260
+ const removeLabelDescription = "Remove a label from an issue or pull request";
1261
+ /** Not idempotent — removing a missing label returns 404 from GitHub. */
1262
+ async function removeLabelCore({ token, owner, repo, issueNumber, label }) {
1263
+ await createOctokit(token).rest.issues.removeLabel({
1264
+ owner,
1265
+ repo,
1266
+ issue_number: issueNumber,
1267
+ name: label
1268
+ });
1269
+ return {
1270
+ removed: true,
1271
+ label,
1272
+ issueNumber
1273
+ };
1274
+ }
1275
+ const addAssigneesInputSchema = z.object({
1276
+ owner: z.string().describe("Repository owner"),
1277
+ repo: z.string().describe("Repository name"),
1278
+ issueNumber: z.number().describe("Issue or pull request number"),
1279
+ assignees: z.array(z.string()).describe("GitHub usernames to assign")
1280
+ });
1281
+ const addAssigneesDescription = "Assign users to an issue or pull request";
1282
+ /** Not idempotent — re-adding an existing assignee is a no-op on GitHub but still mutates. */
1283
+ async function addAssigneesCore({ token, owner, repo, issueNumber, assignees }) {
1284
+ const { data } = await createOctokit(token).rest.issues.addAssignees({
1285
+ owner,
1286
+ repo,
1287
+ issue_number: issueNumber,
1288
+ assignees
1289
+ });
1290
+ return {
1291
+ number: data.number,
1292
+ assignees: data.assignees?.map((a) => a.login)
1293
+ };
1294
+ }
1295
+ const removeAssigneesInputSchema = z.object({
1296
+ owner: z.string().describe("Repository owner"),
1297
+ repo: z.string().describe("Repository name"),
1298
+ issueNumber: z.number().describe("Issue or pull request number"),
1299
+ assignees: z.array(z.string()).describe("GitHub usernames to unassign")
1300
+ });
1301
+ const removeAssigneesDescription = "Remove assignees from an issue or pull request";
1302
+ /** Idempotent — removing an assignee that is not assigned is a no-op on GitHub. */
1303
+ async function removeAssigneesCore({ token, owner, repo, issueNumber, assignees }) {
1304
+ const { data } = await createOctokit(token).rest.issues.removeAssignees({
1305
+ owner,
1306
+ repo,
1307
+ issue_number: issueNumber,
1308
+ assignees
1309
+ });
1310
+ return {
1311
+ number: data.number,
1312
+ assignees: data.assignees?.map((a) => a.login)
1313
+ };
1314
+ }
1315
+ //#endregion
1316
+ //#region src/core/reactions.ts
1317
+ const reactionContentSchema = z.enum([
1318
+ "+1",
1319
+ "-1",
1320
+ "laugh",
1321
+ "confused",
1322
+ "heart",
1323
+ "hooray",
1324
+ "rocket",
1325
+ "eyes"
1326
+ ]);
1327
+ function shapeReactions(reactions) {
1328
+ const counts = {};
1329
+ for (const reaction of reactions) counts[reaction.content] = (counts[reaction.content] ?? 0) + 1;
1330
+ return {
1331
+ total: reactions.length,
1332
+ counts,
1333
+ reactions: reactions.map((reaction) => ({
1334
+ content: reaction.content,
1335
+ user: reaction.user?.login
1336
+ }))
1337
+ };
1338
+ }
1339
+ const listIssueReactionsInputSchema = z.object({
1340
+ owner: z.string().describe("Repository owner"),
1341
+ repo: z.string().describe("Repository name"),
1342
+ issueNumber: z.number().describe("Issue or pull request number — pull request conversations share the issue numbering"),
1343
+ content: reactionContentSchema.optional().describe("Only return reactions of this type"),
1344
+ perPage: z.number().optional().default(30).describe("Number of reactions to return (max 100)"),
1345
+ page: z.number().optional().default(1).describe("Page number for pagination")
1346
+ });
1347
+ const listIssueReactionsDescription = "List reactions on an issue or pull request conversation, with per-emoji counts for the returned page";
1348
+ async function listIssueReactionsCore({ token, owner, repo, issueNumber, content, perPage, page }) {
1349
+ const { data } = await createOctokit(token).rest.reactions.listForIssue({
1350
+ owner,
1351
+ repo,
1352
+ issue_number: issueNumber,
1353
+ content,
1354
+ per_page: perPage,
1355
+ page
1356
+ });
1357
+ return shapeReactions(data);
1358
+ }
1359
+ const addIssueReactionInputSchema = z.object({
1360
+ owner: z.string().describe("Repository owner"),
1361
+ repo: z.string().describe("Repository name"),
1362
+ issueNumber: z.number().describe("Issue or pull request number — pull request conversations share the issue numbering"),
1363
+ content: reactionContentSchema.describe("Reaction to add")
1364
+ });
1365
+ const addIssueReactionDescription = "React to an issue or pull request with an emoji. Prefer this over posting a comment to acknowledge a report without adding noise to the thread";
1366
+ /** Idempotent — GitHub returns the existing reaction when the user already reacted with the same content. */
1367
+ async function addIssueReactionCore({ token, owner, repo, issueNumber, content }) {
1368
+ const { data } = await createOctokit(token).rest.reactions.createForIssue({
1369
+ owner,
1370
+ repo,
1371
+ issue_number: issueNumber,
1372
+ content
1373
+ });
1374
+ return {
1375
+ id: data.id,
1376
+ content: data.content,
1377
+ user: data.user?.login,
1378
+ issueNumber
1379
+ };
1380
+ }
1381
+ const listCommentReactionsInputSchema = z.object({
1382
+ owner: z.string().describe("Repository owner"),
1383
+ repo: z.string().describe("Repository name"),
1384
+ commentId: z.number().describe("Issue or pull request comment ID (from getIssueContext or addIssueComment)"),
1385
+ content: reactionContentSchema.optional().describe("Only return reactions of this type"),
1386
+ perPage: z.number().optional().default(30).describe("Number of reactions to return (max 100)"),
1387
+ page: z.number().optional().default(1).describe("Page number for pagination")
1388
+ });
1389
+ const listCommentReactionsDescription = "List reactions on an issue or pull request comment, with per-emoji counts for the returned page";
1390
+ async function listCommentReactionsCore({ token, owner, repo, commentId, content, perPage, page }) {
1391
+ const { data } = await createOctokit(token).rest.reactions.listForIssueComment({
1392
+ owner,
1393
+ repo,
1394
+ comment_id: commentId,
1395
+ content,
1396
+ per_page: perPage,
1397
+ page
1398
+ });
1399
+ return shapeReactions(data);
1400
+ }
1401
+ const addCommentReactionInputSchema = z.object({
1402
+ owner: z.string().describe("Repository owner"),
1403
+ repo: z.string().describe("Repository name"),
1404
+ commentId: z.number().describe("Issue or pull request comment ID to react to"),
1405
+ content: reactionContentSchema.describe("Reaction to add")
1406
+ });
1407
+ const addCommentReactionDescription = "React to an issue or pull request comment with an emoji. Prefer this over a reply when acknowledging a comment";
1408
+ /** Idempotent — GitHub returns the existing reaction when the user already reacted with the same content. */
1409
+ async function addCommentReactionCore({ token, owner, repo, commentId, content }) {
1410
+ const { data } = await createOctokit(token).rest.reactions.createForIssueComment({
1411
+ owner,
1412
+ repo,
1413
+ comment_id: commentId,
1414
+ content
1415
+ });
1416
+ return {
1417
+ id: data.id,
1418
+ content: data.content,
1419
+ user: data.user?.login,
1420
+ commentId
1421
+ };
1422
+ }
1423
+ //#endregion
1424
+ //#region src/core/discussions.ts
1425
+ const DISCUSSION_CATEGORIES_QUERY = `
1426
+ query ($owner: String!, $name: String!) {
1427
+ repository(owner: $owner, name: $name) {
1428
+ discussionCategories(first: 100) {
1429
+ nodes {
1430
+ id
1431
+ name
1432
+ }
1433
+ }
1434
+ }
1435
+ }
1436
+ `;
1437
+ const LIST_DISCUSSIONS_QUERY = `
1438
+ query ($owner: String!, $name: String!, $first: Int!, $after: String, $categoryId: ID) {
1439
+ repository(owner: $owner, name: $name) {
1440
+ discussions(first: $first, after: $after, categoryId: $categoryId, orderBy: { field: UPDATED_AT, direction: DESC }) {
1441
+ pageInfo {
1442
+ hasNextPage
1443
+ endCursor
1444
+ }
1445
+ nodes {
1446
+ id
1447
+ number
1448
+ title
1449
+ url
1450
+ createdAt
1451
+ updatedAt
1452
+ isAnswered
1453
+ author {
1454
+ login
1455
+ }
1456
+ category {
1457
+ name
1458
+ }
1459
+ }
1460
+ }
1461
+ }
1462
+ }
1463
+ `;
1464
+ const GET_DISCUSSION_QUERY = `
1465
+ query ($owner: String!, $name: String!, $number: Int!) {
1466
+ repository(owner: $owner, name: $name) {
1467
+ discussion(number: $number) {
1468
+ id
1469
+ number
1470
+ title
1471
+ body
1472
+ url
1473
+ createdAt
1474
+ updatedAt
1475
+ isAnswered
1476
+ author {
1477
+ login
1478
+ }
1479
+ category {
1480
+ name
1481
+ }
1482
+ comments {
1483
+ totalCount
1484
+ }
1485
+ }
1486
+ }
1487
+ }
1488
+ `;
1489
+ const DISCUSSION_ID_QUERY = `
1490
+ query ($owner: String!, $name: String!, $number: Int!) {
1491
+ repository(owner: $owner, name: $name) {
1492
+ discussion(number: $number) {
1493
+ id
1494
+ }
1495
+ }
1496
+ }
1497
+ `;
1498
+ const ADD_DISCUSSION_COMMENT_MUTATION = `
1499
+ mutation ($discussionId: ID!, $body: String!) {
1500
+ addDiscussionComment(input: { discussionId: $discussionId, body: $body }) {
1501
+ comment {
1502
+ id
1503
+ url
1504
+ body
1505
+ createdAt
1506
+ author {
1507
+ login
1508
+ }
1509
+ }
1510
+ }
1511
+ }
1512
+ `;
1513
+ async function resolveCategoryId(octokit, owner, repo, category) {
1514
+ const nodes = (await octokit.graphql(DISCUSSION_CATEGORIES_QUERY, {
1515
+ owner,
1516
+ name: repo
1517
+ })).repository?.discussionCategories.nodes ?? [];
1518
+ return {
1519
+ id: nodes.find((node) => node.name.toLowerCase() === category.toLowerCase())?.id,
1520
+ available: nodes.map((node) => node.name)
1521
+ };
1522
+ }
1523
+ const listDiscussionsInputSchema = z.object({
1524
+ owner: z.string().describe("Repository owner"),
1525
+ repo: z.string().describe("Repository name"),
1526
+ category: z.string().optional().describe("Discussion category name (for example \"Q&A\" or \"Ideas\") — omit for all categories"),
1527
+ perPage: z.number().optional().default(20).describe("Number of discussions to return (max 100)"),
1528
+ after: z.string().optional().describe("Cursor from a previous call (endCursor) to fetch the next page")
1529
+ });
1530
+ const listDiscussionsDescription = "List discussions in a GitHub repository, most recently updated first, optionally filtered by category (GitHub GraphQL API)";
1531
+ async function listDiscussionsCore({ token, owner, repo, category, perPage, after }) {
1532
+ const octokit = createOctokit(token);
1533
+ let categoryId;
1534
+ if (category) {
1535
+ const { id, available } = await resolveCategoryId(octokit, owner, repo, category);
1536
+ if (!id) return { error: `Unknown discussion category "${category}". Available categories: ${available.join(", ")}` };
1537
+ categoryId = id;
1538
+ }
1539
+ const data = await octokit.graphql(LIST_DISCUSSIONS_QUERY, {
1540
+ owner,
1541
+ name: repo,
1542
+ first: perPage,
1543
+ after,
1544
+ categoryId
1545
+ });
1546
+ if (!data.repository) return { error: `Repository not found, or discussions are disabled on ${owner}/${repo}` };
1547
+ const { pageInfo, nodes } = data.repository.discussions;
1548
+ return {
1549
+ hasNextPage: pageInfo.hasNextPage,
1550
+ endCursor: pageInfo.endCursor,
1551
+ discussions: nodes.map((node) => ({
1552
+ id: node.id,
1553
+ number: node.number,
1554
+ title: node.title,
1555
+ url: node.url,
1556
+ author: node.author?.login ?? null,
1557
+ category: node.category?.name ?? null,
1558
+ answerChosen: node.isAnswered,
1559
+ createdAt: node.createdAt,
1560
+ updatedAt: node.updatedAt
1561
+ }))
1562
+ };
1563
+ }
1564
+ const getDiscussionInputSchema = z.object({
1565
+ owner: z.string().describe("Repository owner"),
1566
+ repo: z.string().describe("Repository name"),
1567
+ discussionNumber: z.number().describe("Discussion number"),
1568
+ detail: detailSchema
1569
+ });
1570
+ const getDiscussionDescription = "Get a GitHub discussion by number. Body is truncated by default (detail: summary) — set detail full for the complete text (GitHub GraphQL API)";
1571
+ async function getDiscussionCore({ token, owner, repo, discussionNumber, detail = "summary" }) {
1572
+ const discussion = (await createOctokit(token).graphql(GET_DISCUSSION_QUERY, {
1573
+ owner,
1574
+ name: repo,
1575
+ number: discussionNumber
1576
+ })).repository?.discussion;
1577
+ if (!discussion) return { error: `Discussion #${discussionNumber} not found on ${owner}/${repo}` };
1578
+ return {
1579
+ id: discussion.id,
1580
+ number: discussion.number,
1581
+ title: discussion.title,
1582
+ body: applyDetailBody(discussion.body, detail),
1583
+ url: discussion.url,
1584
+ author: discussion.author?.login ?? null,
1585
+ category: discussion.category?.name ?? null,
1586
+ answerChosen: discussion.isAnswered,
1587
+ commentsCount: discussion.comments.totalCount,
1588
+ createdAt: discussion.createdAt,
1589
+ updatedAt: discussion.updatedAt
1590
+ };
1591
+ }
1592
+ const addDiscussionCommentInputSchema = z.object({
1593
+ owner: z.string().describe("Repository owner"),
1594
+ repo: z.string().describe("Repository name"),
1595
+ discussionNumber: z.number().describe("Discussion number"),
1596
+ body: z.string().describe("Comment text (supports Markdown)")
1597
+ });
1598
+ const addDiscussionCommentDescription = "Add a comment to a GitHub discussion (GitHub GraphQL API)";
1599
+ /** Not idempotent — each call adds another comment. */
1600
+ async function addDiscussionCommentCore({ token, owner, repo, discussionNumber, body }) {
1601
+ const octokit = createOctokit(token);
1602
+ const discussionId = (await octokit.graphql(DISCUSSION_ID_QUERY, {
1603
+ owner,
1604
+ name: repo,
1605
+ number: discussionNumber
1606
+ })).repository?.discussion?.id;
1607
+ if (!discussionId) return { error: `Discussion #${discussionNumber} not found on ${owner}/${repo}` };
1608
+ const comment = (await octokit.graphql(ADD_DISCUSSION_COMMENT_MUTATION, {
1609
+ discussionId,
1610
+ body
1611
+ })).addDiscussionComment.comment;
1612
+ return {
1613
+ id: comment.id,
1614
+ url: comment.url,
1615
+ body: comment.body,
1616
+ author: comment.author?.login ?? null,
1617
+ createdAt: comment.createdAt
1618
+ };
1619
+ }
1620
+ //#endregion
1621
+ //#region src/core/notifications.ts
1622
+ const listNotificationsInputSchema = z.object({
1623
+ all: z.boolean().optional().default(false).describe("Include notifications already marked as read"),
1624
+ participating: z.boolean().optional().default(false).describe("Only notifications where the authenticated user is directly participating or mentioned"),
1625
+ perPage: z.number().optional().default(20).describe("Number of notifications to return (max 50)"),
1626
+ page: z.number().optional().default(1).describe("Page number for pagination")
1627
+ });
1628
+ const listNotificationsDescription = "List notification threads for the authenticated user. Unread only by default — set all true to include read threads. Requires a token with notifications access";
1629
+ async function listNotificationsCore({ token, all, participating, perPage, page }) {
1630
+ const { data } = await createOctokit(token).rest.activity.listNotificationsForAuthenticatedUser({
1631
+ all,
1632
+ participating,
1633
+ per_page: perPage,
1634
+ page
1635
+ });
1636
+ return data.map((thread) => ({
1637
+ threadId: thread.id,
1638
+ repository: thread.repository.full_name,
1639
+ subject: {
1640
+ title: thread.subject.title,
1641
+ type: thread.subject.type,
1642
+ url: thread.subject.url
1643
+ },
1644
+ reason: thread.reason,
1645
+ unread: thread.unread,
1646
+ updatedAt: thread.updated_at
1647
+ }));
1648
+ }
1649
+ const markNotificationReadInputSchema = z.object({ threadId: z.string().describe("Notification thread ID (from listNotifications)") });
1650
+ const markNotificationReadDescription = "Mark a single notification thread as read";
1651
+ /** Idempotent — marking an already-read thread is a no-op on GitHub. */
1652
+ async function markNotificationReadCore({ token, threadId }) {
1653
+ await createOctokit(token).rest.activity.markThreadAsRead({ thread_id: Number(threadId) });
1654
+ return {
1655
+ marked: true,
1656
+ threadId
1657
+ };
1658
+ }
1659
+ //#endregion
1660
+ //#region src/core/search.ts
1661
+ const MAX_FRAGMENT_LENGTH = 300;
1662
+ function truncateFragment(fragment) {
1663
+ if (fragment.length <= MAX_FRAGMENT_LENGTH) return fragment;
1664
+ return `${fragment.slice(0, MAX_FRAGMENT_LENGTH)}…`;
1665
+ }
1666
+ const searchCodeInputSchema = z.object({
1667
+ query: z.string().describe("Search query. Supports GitHub search qualifiers, e.g. \"useState repo:facebook/react\""),
1668
+ perPage: z.number().optional().default(10).describe("Number of results to return (max 30)")
1669
+ });
1670
+ const searchCodeDescription = "Search for code in GitHub repositories. Use qualifiers like \"repo:owner/name\" to scope the search. Results include matching text snippets when GitHub returns them.";
1671
+ async function searchCodeCore({ token, query, perPage }) {
1672
+ const { data } = await createOctokit(token).rest.search.code({
1673
+ q: query,
1674
+ per_page: perPage,
1675
+ mediaType: { format: "text-match" }
1676
+ });
1677
+ return {
1678
+ totalCount: data.total_count,
1679
+ items: data.items.map((item) => ({
1680
+ name: item.name,
1681
+ path: item.path,
1682
+ url: item.html_url,
1683
+ repository: item.repository.full_name,
1684
+ sha: item.sha,
1685
+ textMatches: item.text_matches?.map((match) => ({ fragment: truncateFragment(match.fragment ?? "") }))
1686
+ }))
1687
+ };
1688
+ }
1689
+ const searchRepositoriesInputSchema = z.object({
1690
+ query: z.string().describe("Search query. Supports GitHub search qualifiers, e.g. \"nuxt language:typescript stars:>1000\""),
1691
+ perPage: z.number().optional().default(10).describe("Number of results to return (max 30)"),
1692
+ sort: z.enum([
1693
+ "stars",
1694
+ "forks",
1695
+ "help-wanted-issues",
1696
+ "updated"
1697
+ ]).optional().describe("Sort field"),
1698
+ order: z.enum(["asc", "desc"]).optional().default("desc").describe("Sort order")
1699
+ });
1700
+ const searchRepositoriesDescription = "Search for GitHub repositories by keyword, topic, language, or other qualifiers";
1701
+ async function searchRepositoriesCore({ token, query, perPage, sort, order }) {
1702
+ const { data } = await createOctokit(token).rest.search.repos({
1703
+ q: query,
1704
+ per_page: perPage,
1705
+ sort,
1706
+ order
1707
+ });
1708
+ return {
1709
+ totalCount: data.total_count,
1710
+ items: data.items.map((repo) => ({
1711
+ name: repo.name,
1712
+ fullName: repo.full_name,
1713
+ description: repo.description,
1714
+ url: repo.html_url,
1715
+ stars: repo.stargazers_count,
1716
+ forks: repo.forks_count,
1717
+ language: repo.language,
1718
+ topics: repo.topics
1719
+ }))
1720
+ };
1721
+ }
1722
+ const searchIssuesInputSchema = z.object({
1723
+ query: z.string().describe("Search query. Supports GitHub search qualifiers, e.g. \"repo:owner/name is:open label:bug\". Returns both issues and pull requests by default — use type:pr or is:pr to scope to pull requests, or type:issue / is:issue to exclude them"),
1724
+ perPage: z.number().optional().default(10).describe("Number of results to return (max 30)"),
1725
+ sort: z.enum([
1726
+ "comments",
1727
+ "reactions",
1728
+ "created",
1729
+ "updated",
1730
+ "interactions"
1731
+ ]).optional().describe("Sort field"),
1732
+ order: z.enum(["asc", "desc"]).optional().default("desc").describe("Sort order")
1733
+ });
1734
+ const searchIssuesDescription = "Search for issues and pull requests across GitHub using search qualifiers like \"repo:owner/name is:open\"";
1735
+ async function searchIssuesCore({ token, query, perPage, sort, order }) {
1736
+ const { data } = await createOctokit(token).rest.search.issuesAndPullRequests({
1737
+ q: query,
1738
+ per_page: perPage,
1739
+ sort,
1740
+ order
1741
+ });
1742
+ return {
1743
+ totalCount: data.total_count,
1744
+ items: data.items.map((item) => ({
1745
+ number: item.number,
1746
+ title: item.title,
1747
+ state: item.state,
1748
+ url: item.html_url,
1749
+ repository: item.repository_url.split("/repos/").at(-1),
1750
+ author: item.user?.login,
1751
+ labels: item.labels.map((l) => typeof l === "string" ? l : l.name),
1752
+ comments: item.comments,
1753
+ createdAt: item.created_at,
1754
+ updatedAt: item.updated_at,
1755
+ isPullRequest: Boolean(item.pull_request)
1756
+ }))
1757
+ };
1758
+ }
1759
+ //#endregion
1760
+ //#region src/core/commits.ts
1761
+ const BLAME_QUERY = `
1762
+ query ($owner: String!, $name: String!, $expression: String!, $path: String!) {
1763
+ repository(owner: $owner, name: $name) {
1764
+ object(expression: $expression) {
1765
+ ... on Commit {
1766
+ oid
1767
+ blame(path: $path) {
1768
+ ranges {
1769
+ startingLine
1770
+ endingLine
1771
+ age
1772
+ commit {
1773
+ oid
1774
+ abbreviatedOid
1775
+ messageHeadline
1776
+ authoredDate
1777
+ url
1778
+ author {
1779
+ name
1780
+ email
1781
+ user {
1782
+ login
1783
+ }
1784
+ }
1785
+ }
1786
+ }
1787
+ }
1788
+ }
1789
+ }
1790
+ }
1791
+ }
1792
+ `;
1793
+ const listCommitsInputSchema = z.object({
1794
+ owner: z.string().describe("Repository owner"),
1795
+ repo: z.string().describe("Repository name"),
1796
+ path: z.string().optional().describe("Only commits containing this file path"),
1797
+ sha: z.string().optional().describe("Branch name or commit SHA to start listing from"),
1798
+ author: z.string().optional().describe("GitHub username or email to filter commits by"),
1799
+ since: z.string().optional().describe("Only commits after this date (ISO 8601 format)"),
1800
+ until: z.string().optional().describe("Only commits before this date (ISO 8601 format)"),
1801
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
1802
+ maxPages: maxPagesSchema
1803
+ });
1804
+ const listCommitsDescription = "List commits for a GitHub repository. Filter by file path to see commits that touched a file. For line-by-line attribution at a given ref, use getBlame instead.";
1805
+ async function listCommitsCore({ token, owner, repo, path, sha, author, since, until, perPage, maxPages }) {
1806
+ const octokit = createOctokit(token);
1807
+ return (await fetchAllPages(async (page) => {
1808
+ const { data } = await octokit.rest.repos.listCommits({
1809
+ owner,
1810
+ repo,
1811
+ path,
1812
+ sha,
1813
+ author,
1814
+ since,
1815
+ until,
1816
+ per_page: perPage,
1817
+ page
1818
+ });
1819
+ return data;
1820
+ }, perPage, maxPages)).map((commit) => ({
1821
+ sha: commit.sha,
1822
+ message: commit.commit.message,
1823
+ author: commit.commit.author?.name,
1824
+ authorLogin: commit.author?.login,
1825
+ date: commit.commit.author?.date,
1826
+ url: commit.html_url
1827
+ }));
1828
+ }
1829
+ const getCommitInputSchema = z.object({
1830
+ owner: z.string().describe("Repository owner"),
1831
+ repo: z.string().describe("Repository name"),
1832
+ ref: z.string().describe("Commit SHA, branch name, or tag"),
1833
+ includePatch: z.boolean().optional().default(false).describe("Include diff patches for changed files (token-heavy). Prefer false unless you need the diffs")
1834
+ });
1835
+ const getCommitDescription = "Get detailed information about a specific commit, including the list of files changed with additions and deletions. Patches are omitted by default — set includePatch true to include diffs";
1836
+ async function getCommitCore({ token, owner, repo, ref, includePatch }) {
1837
+ const { data } = await createOctokit(token).rest.repos.getCommit({
1838
+ owner,
1839
+ repo,
1840
+ ref
1841
+ });
1842
+ return {
1843
+ sha: data.sha,
1844
+ message: data.commit.message,
1845
+ author: data.commit.author?.name,
1846
+ authorLogin: data.author?.login,
1847
+ date: data.commit.author?.date,
1848
+ url: data.html_url,
1849
+ stats: data.stats ? {
1850
+ additions: data.stats.additions,
1851
+ deletions: data.stats.deletions,
1852
+ total: data.stats.total
1853
+ } : null,
1854
+ files: data.files?.map((file) => ({
1855
+ filename: file.filename,
1856
+ status: file.status,
1857
+ additions: file.additions,
1858
+ deletions: file.deletions,
1859
+ ...includePatch && file.patch != null ? { patch: file.patch } : {}
1860
+ }))
1861
+ };
1862
+ }
1863
+ const getBlameInputSchema = z.object({
1864
+ owner: z.string().describe("Repository owner"),
1865
+ repo: z.string().describe("Repository name"),
1866
+ path: z.string().describe("Path to the file in the repository"),
1867
+ ref: z.string().optional().describe("Branch name, tag, or commit SHA (defaults to the repository default branch)"),
1868
+ line: z.number().int().positive().optional().describe("If set, only return blame ranges that include this line number"),
1869
+ lineStart: z.number().int().positive().optional().describe("When used with lineEnd, only return ranges overlapping this window"),
1870
+ lineEnd: z.number().int().positive().optional().describe("When used with lineStart, only return ranges overlapping this window")
1871
+ });
1872
+ const getBlameDescription = "Line-level git blame for a file at a commit-like ref (branch, tag, or SHA). Returns contiguous ranges mapping lines to the commits that last modified them — use this to see who introduced a line and when (GitHub GraphQL API).";
1873
+ async function getBlameCore({ token, owner, repo, path, ref, line, lineStart, lineEnd }) {
1874
+ const octokit = createOctokit(token);
1875
+ let expression = ref;
1876
+ if (!expression) {
1877
+ const { data } = await octokit.rest.repos.get({
1878
+ owner,
1879
+ repo
1880
+ });
1881
+ expression = data.default_branch;
1882
+ }
1883
+ const data = await octokit.graphql(BLAME_QUERY, {
1884
+ owner,
1885
+ name: repo,
1886
+ expression,
1887
+ path
1888
+ });
1889
+ if (!data.repository) return { error: `Repository not found: ${owner}/${repo}` };
1890
+ const obj = data.repository.object;
1891
+ if (!obj?.oid || !obj?.blame) return { error: `Ref "${expression}" did not resolve to a commit for this repository (or the path is invalid). Pass a branch name, tag, or full commit SHA.` };
1892
+ let ranges = obj.blame.ranges.map((r) => ({
1893
+ startingLine: r.startingLine,
1894
+ endingLine: r.endingLine,
1895
+ age: r.age,
1896
+ commit: {
1897
+ sha: r.commit.oid,
1898
+ abbreviatedSha: r.commit.abbreviatedOid,
1899
+ messageHeadline: r.commit.messageHeadline,
1900
+ authoredDate: r.commit.authoredDate,
1901
+ url: r.commit.url,
1902
+ authorName: r.commit.author?.name ?? null,
1903
+ authorEmail: r.commit.author?.email ?? null,
1904
+ authorLogin: r.commit.author?.user?.login ?? null
1905
+ }
1906
+ }));
1907
+ if (line != null) ranges = ranges.filter((r) => line >= r.startingLine && line <= r.endingLine);
1908
+ else if (lineStart != null || lineEnd != null) {
1909
+ const start = lineStart ?? 1;
1910
+ const end = lineEnd ?? Number.MAX_SAFE_INTEGER;
1911
+ ranges = ranges.filter((r) => r.endingLine >= start && r.startingLine <= end);
1912
+ }
1913
+ return {
1914
+ ref: expression,
1915
+ tipSha: obj.oid,
1916
+ path,
1917
+ rangeCount: ranges.length,
1918
+ ranges
1919
+ };
1920
+ }
1921
+ const compareCommitsInputSchema = z.object({
1922
+ owner: z.string().describe("Repository owner"),
1923
+ repo: z.string().describe("Repository name"),
1924
+ base: z.string().describe("Base branch, tag, or commit SHA"),
1925
+ head: z.string().describe("Head branch, tag, or commit SHA to compare against base"),
1926
+ includePatch: z.boolean().optional().default(false).describe("Include diff patches for changed files (token-heavy). Prefer false unless you need the diffs")
1927
+ });
1928
+ const compareCommitsDescription = "Compare two branches, tags, or commits — shows ahead/behind counts, the commits in between, and the files that differ. Patches are omitted by default — set includePatch true to include diffs";
1929
+ async function compareCommitsCore({ token, owner, repo, base, head, includePatch }) {
1930
+ const { data } = await createOctokit(token).rest.repos.compareCommitsWithBasehead({
1931
+ owner,
1932
+ repo,
1933
+ basehead: `${base}...${head}`
1934
+ });
1935
+ return {
1936
+ status: data.status,
1937
+ aheadBy: data.ahead_by,
1938
+ behindBy: data.behind_by,
1939
+ totalCommits: data.total_commits,
1940
+ url: data.html_url,
1941
+ commits: data.commits.map((commit) => ({
1942
+ sha: commit.sha,
1943
+ message: commit.commit.message,
1944
+ author: commit.commit.author?.name,
1945
+ authorLogin: commit.author?.login
1946
+ })),
1947
+ files: data.files?.map((file) => ({
1948
+ filename: file.filename,
1949
+ status: file.status,
1950
+ additions: file.additions,
1951
+ deletions: file.deletions,
1952
+ ...includePatch && file.patch != null ? { patch: file.patch } : {}
1953
+ }))
1954
+ };
1955
+ }
1956
+ //#endregion
1957
+ //#region src/core/gists.ts
1958
+ const listGistsInputSchema = z.object({
1959
+ username: z.string().optional().describe("GitHub username — omit to list your own gists"),
1960
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
1961
+ page: z.number().optional().default(1).describe("Page number for pagination")
1962
+ });
1963
+ const listGistsDescription = "List gists for the authenticated user or a specific user";
1964
+ async function listGistsCore({ token, username, perPage, page }) {
1965
+ const octokit = createOctokit(token);
1966
+ const { data } = username ? await octokit.rest.gists.listForUser({
1967
+ username,
1968
+ per_page: perPage,
1969
+ page
1970
+ }) : await octokit.rest.gists.list({
1971
+ per_page: perPage,
1972
+ page
1973
+ });
1974
+ return data.map((gist) => ({
1975
+ id: gist.id,
1976
+ description: gist.description,
1977
+ public: gist.public,
1978
+ url: gist.html_url,
1979
+ files: Object.keys(gist.files ?? {}),
1980
+ owner: gist.owner?.login,
1981
+ comments: gist.comments,
1982
+ createdAt: gist.created_at,
1983
+ updatedAt: gist.updated_at
1984
+ }));
1985
+ }
1986
+ const getGistInputSchema = z.object({ gistId: z.string().describe("Gist ID") });
1987
+ const getGistDescription = "Get a gist by ID, including file contents";
1988
+ async function getGistCore({ token, gistId }) {
1989
+ const { data } = await createOctokit(token).rest.gists.get({ gist_id: gistId });
1990
+ return {
1991
+ id: data.id,
1992
+ description: data.description,
1993
+ public: data.public,
1994
+ url: data.html_url,
1995
+ owner: data.owner?.login,
1996
+ files: Object.values(data.files ?? {}).map((file) => ({
1997
+ filename: file?.filename,
1998
+ language: file?.language,
1999
+ size: file?.size,
2000
+ content: file?.content
2001
+ })),
2002
+ comments: data.comments,
2003
+ createdAt: data.created_at,
2004
+ updatedAt: data.updated_at
2005
+ };
2006
+ }
2007
+ const listGistCommentsInputSchema = z.object({
2008
+ gistId: z.string().describe("Gist ID"),
2009
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
2010
+ page: z.number().optional().default(1).describe("Page number for pagination")
2011
+ });
2012
+ const listGistCommentsDescription = "List comments on a gist";
2013
+ async function listGistCommentsCore({ token, gistId, perPage, page }) {
2014
+ const { data } = await createOctokit(token).rest.gists.listComments({
2015
+ gist_id: gistId,
2016
+ per_page: perPage,
2017
+ page
2018
+ });
2019
+ return data.map((comment) => ({
2020
+ id: comment.id,
2021
+ body: comment.body,
2022
+ author: comment.user?.login,
2023
+ url: comment.url,
2024
+ createdAt: comment.created_at,
2025
+ updatedAt: comment.updated_at
2026
+ }));
2027
+ }
2028
+ const createGistInputSchema = z.object({
2029
+ description: z.string().optional().describe("Gist description"),
2030
+ files: z.record(z.string(), z.object({ content: z.string().describe("File content") })).describe("Files to include, keyed by filename"),
2031
+ isPublic: z.boolean().optional().default(false).describe("Whether the gist is public")
2032
+ });
2033
+ const createGistDescription = "Create a new gist with one or more files";
2034
+ /** Not idempotent — each call creates a new gist. */
2035
+ async function createGistCore({ token, description, files, isPublic }) {
2036
+ const { data } = await createOctokit(token).rest.gists.create({
2037
+ description,
2038
+ files,
2039
+ public: isPublic
2040
+ });
2041
+ return {
2042
+ id: data.id,
2043
+ description: data.description,
2044
+ public: data.public,
2045
+ url: data.html_url,
2046
+ files: Object.keys(data.files ?? {}),
2047
+ owner: data.owner?.login
2048
+ };
2049
+ }
2050
+ const updateGistInputSchema = z.object({
2051
+ gistId: z.string().describe("Gist ID"),
2052
+ description: z.string().optional().describe("New gist description"),
2053
+ files: z.record(z.string(), z.object({ content: z.string().describe("New file content") })).optional().describe("Files to add or update, keyed by filename"),
2054
+ filesToDelete: z.array(z.string()).optional().describe("Filenames to remove from the gist")
2055
+ });
2056
+ const updateGistDescription = "Update an existing gist — edit description, update files, or remove files";
2057
+ /** Not idempotent — each call applies a new revision. */
2058
+ async function updateGistCore({ token, gistId, description, files, filesToDelete }) {
2059
+ const octokit = createOctokit(token);
2060
+ const fileUpdates = {};
2061
+ if (files) Object.assign(fileUpdates, files);
2062
+ if (filesToDelete) for (const name of filesToDelete) fileUpdates[name] = null;
2063
+ const { data } = await octokit.rest.gists.update({
2064
+ gist_id: gistId,
2065
+ description,
2066
+ files: fileUpdates
2067
+ });
2068
+ return {
2069
+ id: data.id,
2070
+ description: data.description,
2071
+ url: data.html_url,
2072
+ files: Object.keys(data.files ?? {})
2073
+ };
2074
+ }
2075
+ const deleteGistInputSchema = z.object({ gistId: z.string().describe("Gist ID to delete") });
2076
+ const deleteGistDescription = "Delete a gist permanently";
2077
+ /** Not idempotent — deleting an already-deleted gist returns 404 from GitHub. */
2078
+ async function deleteGistCore({ token, gistId }) {
2079
+ await createOctokit(token).rest.gists.delete({ gist_id: gistId });
2080
+ return {
2081
+ deleted: true,
2082
+ gistId
2083
+ };
2084
+ }
2085
+ const createGistCommentInputSchema = z.object({
2086
+ gistId: z.string().describe("Gist ID"),
2087
+ body: z.string().describe("Comment text (supports Markdown)")
2088
+ });
2089
+ const createGistCommentDescription = "Add a comment to a gist";
2090
+ /** Not idempotent — each call adds another comment. */
2091
+ async function createGistCommentCore({ token, gistId, body }) {
2092
+ const { data } = await createOctokit(token).rest.gists.createComment({
2093
+ gist_id: gistId,
2094
+ body
2095
+ });
2096
+ return {
2097
+ id: data.id,
2098
+ url: data.url,
2099
+ body: data.body,
2100
+ author: data.user?.login,
2101
+ createdAt: data.created_at
2102
+ };
2103
+ }
2104
+ //#endregion
2105
+ //#region src/core/workflows.ts
2106
+ const listWorkflowsInputSchema = z.object({
2107
+ owner: z.string().describe("Repository owner"),
2108
+ repo: z.string().describe("Repository name"),
2109
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
2110
+ page: z.number().optional().default(1).describe("Page number for pagination")
2111
+ });
2112
+ const listWorkflowsDescription = "List GitHub Actions workflows in a repository";
2113
+ async function listWorkflowsCore({ token, owner, repo, perPage, page }) {
2114
+ const { data } = await createOctokit(token).rest.actions.listRepoWorkflows({
2115
+ owner,
2116
+ repo,
2117
+ per_page: perPage,
2118
+ page
2119
+ });
2120
+ return {
2121
+ totalCount: data.total_count,
2122
+ workflows: data.workflows.map((wf) => ({
2123
+ id: wf.id,
2124
+ name: wf.name,
2125
+ path: wf.path,
2126
+ state: wf.state,
2127
+ url: wf.html_url,
2128
+ createdAt: wf.created_at,
2129
+ updatedAt: wf.updated_at
2130
+ }))
2131
+ };
2132
+ }
2133
+ const listWorkflowRunsInputSchema = z.object({
2134
+ owner: z.string().describe("Repository owner"),
2135
+ repo: z.string().describe("Repository name"),
2136
+ workflowId: z.union([z.string(), z.number()]).optional().describe("Workflow ID or filename (e.g. \"ci.yml\") to filter by"),
2137
+ branch: z.string().optional().describe("Branch name to filter by"),
2138
+ event: z.string().optional().describe("Event type to filter by (e.g. \"push\", \"pull_request\")"),
2139
+ status: z.enum([
2140
+ "completed",
2141
+ "action_required",
2142
+ "cancelled",
2143
+ "failure",
2144
+ "neutral",
2145
+ "skipped",
2146
+ "stale",
2147
+ "success",
2148
+ "timed_out",
2149
+ "in_progress",
2150
+ "queued",
2151
+ "requested",
2152
+ "waiting",
2153
+ "pending"
2154
+ ]).optional().describe("Status to filter by"),
2155
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
2156
+ page: z.number().optional().default(1).describe("Page number for pagination"),
2157
+ maxPages: maxPagesSchema
2158
+ });
2159
+ const listWorkflowRunsDescription = "List workflow runs for a repository, optionally filtered by workflow, branch, status, or event";
2160
+ async function listWorkflowRunsCore({ token, owner, repo, workflowId, branch, event, status, perPage, page, maxPages }) {
2161
+ const octokit = createOctokit(token);
2162
+ let totalCount = 0;
2163
+ const runs = await fetchAllPages(async (currentPage) => {
2164
+ const { data } = workflowId ? await octokit.rest.actions.listWorkflowRuns({
2165
+ owner,
2166
+ repo,
2167
+ workflow_id: workflowId,
2168
+ per_page: perPage,
2169
+ page: currentPage,
2170
+ ...branch && { branch },
2171
+ ...event && { event },
2172
+ ...status && { status }
2173
+ }) : await octokit.rest.actions.listWorkflowRunsForRepo({
2174
+ owner,
2175
+ repo,
2176
+ per_page: perPage,
2177
+ page: currentPage,
2178
+ ...branch && { branch },
2179
+ ...event && { event },
2180
+ ...status && { status }
2181
+ });
2182
+ totalCount = data.total_count;
2183
+ return data.workflow_runs;
2184
+ }, perPage, maxPages, page);
2185
+ return {
2186
+ totalCount,
2187
+ runs: runs.map((run) => ({
2188
+ id: run.id,
2189
+ name: run.name,
2190
+ status: run.status,
2191
+ conclusion: run.conclusion,
2192
+ branch: run.head_branch,
2193
+ event: run.event,
2194
+ url: run.html_url,
2195
+ actor: run.actor?.login,
2196
+ createdAt: run.created_at,
2197
+ updatedAt: run.updated_at,
2198
+ runNumber: run.run_number,
2199
+ runAttempt: run.run_attempt
2200
+ }))
2201
+ };
2202
+ }
2203
+ const getWorkflowRunInputSchema = z.object({
2204
+ owner: z.string().describe("Repository owner"),
2205
+ repo: z.string().describe("Repository name"),
2206
+ runId: z.number().describe("Workflow run ID")
2207
+ });
2208
+ const getWorkflowRunDescription = "Get details of a specific workflow run including status, timing, and trigger info";
2209
+ async function getWorkflowRunCore({ token, owner, repo, runId }) {
2210
+ const { data } = await createOctokit(token).rest.actions.getWorkflowRun({
2211
+ owner,
2212
+ repo,
2213
+ run_id: runId
2214
+ });
2215
+ return {
2216
+ id: data.id,
2217
+ name: data.name,
2218
+ status: data.status,
2219
+ conclusion: data.conclusion,
2220
+ branch: data.head_branch,
2221
+ sha: data.head_sha,
2222
+ event: data.event,
2223
+ url: data.html_url,
2224
+ actor: data.actor?.login,
2225
+ runNumber: data.run_number,
2226
+ runAttempt: data.run_attempt,
2227
+ createdAt: data.created_at,
2228
+ updatedAt: data.updated_at,
2229
+ runStartedAt: data.run_started_at
2230
+ };
2231
+ }
2232
+ const listWorkflowJobsInputSchema = z.object({
2233
+ owner: z.string().describe("Repository owner"),
2234
+ repo: z.string().describe("Repository name"),
2235
+ runId: z.number().describe("Workflow run ID"),
2236
+ filter: z.enum(["latest", "all"]).optional().default("latest").describe("Filter by the latest attempt or all attempts"),
2237
+ perPage: z.number().optional().default(30).describe("Number of results to return (max 100)"),
2238
+ page: z.number().optional().default(1).describe("Page number for pagination")
2239
+ });
2240
+ const listWorkflowJobsDescription = "List jobs for a workflow run, including step-level status and timing";
2241
+ async function listWorkflowJobsCore({ token, owner, repo, runId, filter, perPage, page }) {
2242
+ const { data } = await createOctokit(token).rest.actions.listJobsForWorkflowRun({
2243
+ owner,
2244
+ repo,
2245
+ run_id: runId,
2246
+ filter,
2247
+ per_page: perPage,
2248
+ page
2249
+ });
2250
+ return {
2251
+ totalCount: data.total_count,
2252
+ jobs: data.jobs.map((job) => ({
2253
+ id: job.id,
2254
+ name: job.name,
2255
+ status: job.status,
2256
+ conclusion: job.conclusion,
2257
+ url: job.html_url,
2258
+ startedAt: job.started_at,
2259
+ completedAt: job.completed_at,
2260
+ runnerName: job.runner_name,
2261
+ steps: job.steps?.map((step) => ({
2262
+ name: step.name,
2263
+ status: step.status,
2264
+ conclusion: step.conclusion,
2265
+ number: step.number,
2266
+ startedAt: step.started_at,
2267
+ completedAt: step.completed_at
2268
+ }))
2269
+ }))
2270
+ };
2271
+ }
2272
+ const triggerWorkflowInputSchema = z.object({
2273
+ owner: z.string().describe("Repository owner"),
2274
+ repo: z.string().describe("Repository name"),
2275
+ workflowId: z.union([z.string(), z.number()]).describe("Workflow ID or filename (e.g. \"deploy.yml\")"),
2276
+ ref: z.string().describe("Git ref (branch or tag) to run the workflow on"),
2277
+ inputs: z.record(z.string(), z.string()).optional().describe("Input parameters defined in the workflow_dispatch trigger")
2278
+ });
2279
+ const triggerWorkflowDescription = "Trigger a workflow via workflow_dispatch event";
2280
+ /** Not idempotent — each call starts a new workflow run. */
2281
+ async function triggerWorkflowCore({ token, owner, repo, workflowId, ref, inputs }) {
2282
+ await createOctokit(token).rest.actions.createWorkflowDispatch({
2283
+ owner,
2284
+ repo,
2285
+ workflow_id: workflowId,
2286
+ ref,
2287
+ inputs
2288
+ });
2289
+ return {
2290
+ triggered: true,
2291
+ workflowId,
2292
+ ref
2293
+ };
2294
+ }
2295
+ const cancelWorkflowRunInputSchema = z.object({
2296
+ owner: z.string().describe("Repository owner"),
2297
+ repo: z.string().describe("Repository name"),
2298
+ runId: z.number().describe("Workflow run ID to cancel")
2299
+ });
2300
+ const cancelWorkflowRunDescription = "Cancel an in-progress workflow run";
2301
+ /** Not idempotent — cancelling an already-finished run is a no-op on GitHub but still mutates. */
2302
+ async function cancelWorkflowRunCore({ token, owner, repo, runId }) {
2303
+ await createOctokit(token).rest.actions.cancelWorkflowRun({
2304
+ owner,
2305
+ repo,
2306
+ run_id: runId
2307
+ });
2308
+ return {
2309
+ cancelled: true,
2310
+ runId
2311
+ };
2312
+ }
2313
+ const rerunWorkflowRunInputSchema = z.object({
2314
+ owner: z.string().describe("Repository owner"),
2315
+ repo: z.string().describe("Repository name"),
2316
+ runId: z.number().describe("Workflow run ID to re-run"),
2317
+ onlyFailedJobs: z.boolean().optional().default(false).describe("Only re-run failed jobs instead of the entire workflow")
2318
+ });
2319
+ const rerunWorkflowRunDescription = "Re-run a workflow run, optionally only the failed jobs";
2320
+ /** Not idempotent — each call starts another run attempt. */
2321
+ async function rerunWorkflowRunCore({ token, owner, repo, runId, onlyFailedJobs }) {
2322
+ const octokit = createOctokit(token);
2323
+ if (onlyFailedJobs) await octokit.rest.actions.reRunWorkflowFailedJobs({
2324
+ owner,
2325
+ repo,
2326
+ run_id: runId
2327
+ });
2328
+ else await octokit.rest.actions.reRunWorkflow({
2329
+ owner,
2330
+ repo,
2331
+ run_id: runId
2332
+ });
2333
+ return {
2334
+ rerun: true,
2335
+ runId,
2336
+ onlyFailedJobs
2337
+ };
2338
+ }
2339
+ //#endregion
2340
+ //#region src/core/checks.ts
2341
+ const listCheckRunsInputSchema = z.object({
2342
+ owner: z.string().describe("Repository owner"),
2343
+ repo: z.string().describe("Repository name"),
2344
+ ref: z.string().describe("Git ref: branch, tag, or commit SHA"),
2345
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
2346
+ maxPages: maxPagesSchema
2347
+ });
2348
+ const listCheckRunsDescription = "List check runs (Checks API — GitHub Actions and other CI providers) for a commit, branch, or tag";
2349
+ async function listCheckRunsCore({ token, owner, repo, ref, perPage, maxPages }) {
2350
+ const octokit = createOctokit(token);
2351
+ let totalCount = 0;
2352
+ const checkRuns = await fetchAllPages(async (page) => {
2353
+ const { data } = await octokit.rest.checks.listForRef({
2354
+ owner,
2355
+ repo,
2356
+ ref,
2357
+ per_page: perPage,
2358
+ page
2359
+ });
2360
+ totalCount = data.total_count;
2361
+ return data.check_runs;
2362
+ }, perPage, maxPages);
2363
+ return {
2364
+ totalCount,
2365
+ checkRuns: checkRuns.map((run) => ({
2366
+ id: run.id,
2367
+ name: run.name,
2368
+ status: run.status,
2369
+ conclusion: run.conclusion,
2370
+ url: run.html_url,
2371
+ startedAt: run.started_at,
2372
+ completedAt: run.completed_at
2373
+ }))
2374
+ };
2375
+ }
2376
+ const getCombinedStatusInputSchema = z.object({
2377
+ owner: z.string().describe("Repository owner"),
2378
+ repo: z.string().describe("Repository name"),
2379
+ ref: z.string().describe("Git ref: branch, tag, or commit SHA")
2380
+ });
2381
+ const getCombinedStatusDescription = "Get the combined commit status (Statuses API — legacy CI integrations) for a commit, branch, or tag";
2382
+ async function getCombinedStatusCore({ token, owner, repo, ref }) {
2383
+ const { data } = await createOctokit(token).rest.repos.getCombinedStatusForRef({
2384
+ owner,
2385
+ repo,
2386
+ ref
2387
+ });
2388
+ return {
2389
+ state: data.state,
2390
+ totalCount: data.total_count,
2391
+ statuses: data.statuses.map((status) => ({
2392
+ context: status.context,
2393
+ state: status.state,
2394
+ description: status.description,
2395
+ url: status.target_url
2396
+ }))
2397
+ };
2398
+ }
2399
+ //#endregion
2400
+ //#region src/core/releases.ts
2401
+ const listReleasesInputSchema = z.object({
2402
+ owner: z.string().describe("Repository owner"),
2403
+ repo: z.string().describe("Repository name"),
2404
+ perPage: z.number().optional().default(30).describe("Number of results to return per page (max 100)"),
2405
+ maxPages: maxPagesSchema,
2406
+ detail: detailSchema
2407
+ });
2408
+ const listReleasesDescription = "List releases for a GitHub repository, newest first (includes drafts and prereleases). Bodies truncated by default (detail: summary)";
2409
+ async function listReleasesCore({ token, owner, repo, perPage, maxPages, detail = "summary" }) {
2410
+ const octokit = createOctokit(token);
2411
+ return (await fetchAllPages(async (page) => {
2412
+ const { data } = await octokit.rest.repos.listReleases({
2413
+ owner,
2414
+ repo,
2415
+ per_page: perPage,
2416
+ page
2417
+ });
2418
+ return data;
2419
+ }, perPage, maxPages)).map((release) => ({
2420
+ id: release.id,
2421
+ tagName: release.tag_name,
2422
+ name: release.name,
2423
+ body: applyDetailBody(release.body, detail),
2424
+ draft: release.draft,
2425
+ prerelease: release.prerelease,
2426
+ url: release.html_url,
2427
+ author: release.author?.login,
2428
+ createdAt: release.created_at,
2429
+ publishedAt: release.published_at
2430
+ }));
2431
+ }
2432
+ const getLatestReleaseInputSchema = z.object({
2433
+ owner: z.string().describe("Repository owner"),
2434
+ repo: z.string().describe("Repository name"),
2435
+ detail: detailSchema
2436
+ });
2437
+ const getLatestReleaseDescription = "Get the latest published release for a GitHub repository (excludes drafts and prereleases). Body truncated by default (detail: summary)";
2438
+ async function getLatestReleaseCore({ token, owner, repo, detail = "summary" }) {
2439
+ const { data } = await createOctokit(token).rest.repos.getLatestRelease({
2440
+ owner,
2441
+ repo
2442
+ });
2443
+ return {
2444
+ id: data.id,
2445
+ tagName: data.tag_name,
2446
+ name: data.name,
2447
+ body: applyDetailBody(data.body, detail),
2448
+ url: data.html_url,
2449
+ author: data.author?.login,
2450
+ createdAt: data.created_at,
2451
+ publishedAt: data.published_at,
2452
+ assets: data.assets.map((asset) => ({
2453
+ name: asset.name,
2454
+ downloadUrl: asset.browser_download_url,
2455
+ size: asset.size,
2456
+ downloadCount: asset.download_count
2457
+ }))
2458
+ };
2459
+ }
2460
+ const getReleaseInputSchema = z.object({
2461
+ owner: z.string().describe("Repository owner"),
2462
+ repo: z.string().describe("Repository name"),
2463
+ releaseId: z.number().describe("Release ID (from listReleases or getLatestRelease)"),
2464
+ detail: detailSchema
2465
+ });
2466
+ const getReleaseDescription = "Get a specific release by ID, including its assets. Body truncated by default (detail: summary)";
2467
+ async function getReleaseCore({ token, owner, repo, releaseId, detail = "summary" }) {
2468
+ const { data } = await createOctokit(token).rest.repos.getRelease({
2469
+ owner,
2470
+ repo,
2471
+ release_id: releaseId
2472
+ });
2473
+ return {
2474
+ id: data.id,
2475
+ tagName: data.tag_name,
2476
+ name: data.name,
2477
+ body: applyDetailBody(data.body, detail),
2478
+ draft: data.draft,
2479
+ prerelease: data.prerelease,
2480
+ url: data.html_url,
2481
+ author: data.author?.login,
2482
+ createdAt: data.created_at,
2483
+ publishedAt: data.published_at,
2484
+ assets: data.assets.map((asset) => ({
2485
+ name: asset.name,
2486
+ downloadUrl: asset.browser_download_url,
2487
+ size: asset.size,
2488
+ downloadCount: asset.download_count
2489
+ }))
2490
+ };
2491
+ }
2492
+ const createReleaseInputSchema = z.object({
2493
+ owner: z.string().describe("Repository owner"),
2494
+ repo: z.string().describe("Repository name"),
2495
+ tagName: z.string().describe("Tag name for the release (created from target if it does not exist)"),
2496
+ target: z.string().optional().describe("Branch name or commit SHA to tag (defaults to the default branch)"),
2497
+ name: z.string().optional().describe("Release title (defaults to the tag name)"),
2498
+ body: z.string().optional().describe("Release notes (supports Markdown)"),
2499
+ draft: z.boolean().optional().default(false).describe("Create as a draft release"),
2500
+ prerelease: z.boolean().optional().default(false).describe("Mark as a prerelease"),
2501
+ generateReleaseNotes: z.boolean().optional().default(false).describe("Auto-generate release notes from merged pull requests since the last release")
2502
+ });
2503
+ const createReleaseDescription = "Create a new release (and its tag if needed) in a GitHub repository";
2504
+ /** Not idempotent — creating a release with an existing tag name returns an error from GitHub. */
2505
+ async function createReleaseCore({ token, owner, repo, tagName, target, name, body, draft, prerelease, generateReleaseNotes }) {
2506
+ const { data } = await createOctokit(token).rest.repos.createRelease({
2507
+ owner,
2508
+ repo,
2509
+ tag_name: tagName,
2510
+ target_commitish: target,
2511
+ name,
2512
+ body,
2513
+ draft,
2514
+ prerelease,
2515
+ generate_release_notes: generateReleaseNotes
2516
+ });
2517
+ return {
2518
+ id: data.id,
2519
+ tagName: data.tag_name,
2520
+ name: data.name,
2521
+ body: data.body,
2522
+ url: data.html_url,
2523
+ draft: data.draft,
2524
+ prerelease: data.prerelease,
2525
+ createdAt: data.created_at
2526
+ };
2527
+ }
2528
+ const updateReleaseInputSchema = z.object({
2529
+ owner: z.string().describe("Repository owner"),
2530
+ repo: z.string().describe("Repository name"),
2531
+ releaseId: z.number().describe("Release ID (from listReleases or getLatestRelease)"),
2532
+ tagName: z.string().optional().describe("New tag name for the release"),
2533
+ target: z.string().optional().describe("Branch name or commit SHA to tag"),
2534
+ name: z.string().optional().describe("New release title"),
2535
+ body: z.string().optional().describe("New release notes (supports Markdown)"),
2536
+ draft: z.boolean().optional().describe("Mark as a draft release"),
2537
+ prerelease: z.boolean().optional().describe("Mark as a prerelease")
2538
+ });
2539
+ const updateReleaseDescription = "Update an existing release — tag, target, title, notes, draft, or prerelease status";
2540
+ /** Not idempotent — each call applies a new revision. */
2541
+ async function updateReleaseCore({ token, owner, repo, releaseId, tagName, target, name, body, draft, prerelease }) {
2542
+ const { data } = await createOctokit(token).rest.repos.updateRelease({
2543
+ owner,
2544
+ repo,
2545
+ release_id: releaseId,
2546
+ tag_name: tagName,
2547
+ target_commitish: target,
2548
+ name,
2549
+ body,
2550
+ draft,
2551
+ prerelease
2552
+ });
2553
+ return {
2554
+ id: data.id,
2555
+ tagName: data.tag_name,
2556
+ name: data.name,
2557
+ body: data.body,
2558
+ url: data.html_url,
2559
+ draft: data.draft,
2560
+ prerelease: data.prerelease,
2561
+ publishedAt: data.published_at
2562
+ };
2563
+ }
2564
+ const deleteReleaseInputSchema = z.object({
2565
+ owner: z.string().describe("Repository owner"),
2566
+ repo: z.string().describe("Repository name"),
2567
+ releaseId: z.number().describe("Release ID to delete")
2568
+ });
2569
+ const deleteReleaseDescription = "Delete a release permanently (does not delete the underlying git tag)";
2570
+ /** Not idempotent — deleting an already-deleted release returns 404 from GitHub. */
2571
+ async function deleteReleaseCore({ token, owner, repo, releaseId }) {
2572
+ await createOctokit(token).rest.repos.deleteRelease({
2573
+ owner,
2574
+ repo,
2575
+ release_id: releaseId
2576
+ });
2577
+ return {
2578
+ deleted: true,
2579
+ releaseId
2580
+ };
2581
+ }
2582
+ //#endregion
2583
+ //#region src/core/bundles.ts
2584
+ const getPullRequestContextInputSchema = z.object({
2585
+ owner: z.string().describe("Repository owner"),
2586
+ repo: z.string().describe("Repository name"),
2587
+ pullNumber: z.number().describe("Pull request number"),
2588
+ includeFiles: z.boolean().optional().default(true).describe("Include changed files metadata"),
2589
+ includeReviews: z.boolean().optional().default(true).describe("Include existing reviews"),
2590
+ includeChecks: z.boolean().optional().default(false).describe("Include check runs and combined status for the PR head SHA"),
2591
+ includePatch: z.boolean().optional().default(false).describe("Include diff patches in files (token-heavy; prefer false then fetch specific files with listPullRequestFiles)"),
2592
+ filesPerPage: z.number().optional().default(100).describe("Max files to return when includeFiles is true (max 100)"),
2593
+ detail: detailSchema
2594
+ });
2595
+ const getPullRequestContextDescription = "Fetch pull request details plus files, reviews, and optional CI checks in one call — prefer this over separate getPullRequest / listPullRequestFiles / listPullRequestReviews calls";
2596
+ async function getPullRequestContextCore({ token, owner, repo, pullNumber, includeFiles, includeReviews, includeChecks, includePatch, filesPerPage, detail = "summary" }) {
2597
+ const pullRequest = await getPullRequestCore({
2598
+ token,
2599
+ owner,
2600
+ repo,
2601
+ pullNumber,
2602
+ detail
2603
+ });
2604
+ const [files, reviews, checks] = await Promise.all([
2605
+ includeFiles ? listPullRequestFilesCore({
2606
+ token,
2607
+ owner,
2608
+ repo,
2609
+ pullNumber,
2610
+ includePatch,
2611
+ perPage: filesPerPage,
2612
+ page: 1
2613
+ }) : Promise.resolve(void 0),
2614
+ includeReviews ? listPullRequestReviewsCore({
2615
+ token,
2616
+ owner,
2617
+ repo,
2618
+ pullNumber,
2619
+ perPage: 30,
2620
+ page: 1
2621
+ }) : Promise.resolve(void 0),
2622
+ includeChecks ? Promise.all([listCheckRunsCore({
2623
+ token,
2624
+ owner,
2625
+ repo,
2626
+ ref: pullRequest.headSha,
2627
+ perPage: 100,
2628
+ maxPages: 1
2629
+ }), getCombinedStatusCore({
2630
+ token,
2631
+ owner,
2632
+ repo,
2633
+ ref: pullRequest.headSha
2634
+ })]).then(([checkRuns, combinedStatus]) => ({
2635
+ checkRuns,
2636
+ combinedStatus
2637
+ })) : Promise.resolve(void 0)
2638
+ ]);
2639
+ return {
2640
+ pullRequest,
2641
+ ...files !== void 0 ? { files } : {},
2642
+ ...reviews !== void 0 ? { reviews } : {},
2643
+ ...checks !== void 0 ? { checks } : {}
2644
+ };
2645
+ }
2646
+ const getIssueContextInputSchema = z.object({
2647
+ owner: z.string().describe("Repository owner"),
2648
+ repo: z.string().describe("Repository name"),
2649
+ issueNumber: z.number().describe("Issue number"),
2650
+ includeLabels: z.boolean().optional().default(true).describe("Include available repository label names for triage (names only — use listLabels for descriptions)"),
2651
+ includeComments: z.boolean().optional().default(true).describe("Include recent issue comments"),
2652
+ maxComments: z.number().optional().default(5).describe("Max recent comments to include (keep small — fetch more only when needed)"),
2653
+ detail: z.enum(["summary", "full"]).optional().default("full").describe("full returns the complete body (default for this one-shot tool); summary truncates to ~500 chars")
2654
+ });
2655
+ const getIssueContextDescription = "Fetch an issue plus available label names and recent comments in one call — prefer this over separate getIssue / listLabels / comment calls when triaging. Call once; do not re-fetch the same issue.";
2656
+ async function getIssueContextCore({ token, owner, repo, issueNumber, includeLabels, includeComments, maxComments, detail = "full" }) {
2657
+ const [issue, labels, comments] = await Promise.all([
2658
+ getIssueCore({
2659
+ token,
2660
+ owner,
2661
+ repo,
2662
+ issueNumber,
2663
+ detail
2664
+ }),
2665
+ includeLabels ? listLabelsCore({
2666
+ token,
2667
+ owner,
2668
+ repo,
2669
+ perPage: 100,
2670
+ page: 1
2671
+ }) : Promise.resolve(void 0),
2672
+ includeComments ? listIssueCommentsCore({
2673
+ token,
2674
+ owner,
2675
+ repo,
2676
+ issueNumber,
2677
+ perPage: maxComments,
2678
+ page: 1,
2679
+ detail
2680
+ }) : Promise.resolve(void 0)
2681
+ ]);
2682
+ return {
2683
+ issue,
2684
+ ...labels !== void 0 ? { labelNames: labels.map((label) => label.name) } : {},
2685
+ ...comments !== void 0 ? { comments } : {}
2686
+ };
2687
+ }
2688
+ const getReleaseContextInputSchema = z.object({
2689
+ owner: z.string().describe("Repository owner"),
2690
+ repo: z.string().describe("Repository name"),
2691
+ releaseId: z.number().optional().describe("Release ID — omit to use the latest published release"),
2692
+ includePrevious: z.boolean().optional().default(true).describe("Include the previous release for comparison"),
2693
+ includeCompare: z.boolean().optional().default(true).describe("Include a compare between the previous and current release tags"),
2694
+ detail: detailSchema
2695
+ });
2696
+ const getReleaseContextDescription = "Fetch a release (latest or by ID) plus the previous release and tag comparison in one call — prefer this when preparing or reviewing a release";
2697
+ async function getReleaseContextCore({ token, owner, repo, releaseId, includePrevious, includeCompare, detail = "summary" }) {
2698
+ const release = releaseId != null ? await getReleaseCore({
2699
+ token,
2700
+ owner,
2701
+ repo,
2702
+ releaseId,
2703
+ detail
2704
+ }) : await getLatestReleaseCore({
2705
+ token,
2706
+ owner,
2707
+ repo,
2708
+ detail
2709
+ });
2710
+ let previous;
2711
+ if (includePrevious || includeCompare) previous = (await listReleasesCore({
2712
+ token,
2713
+ owner,
2714
+ repo,
2715
+ perPage: 10,
2716
+ maxPages: 1,
2717
+ detail
2718
+ })).find((r) => r.id !== release.id && !r.draft);
2719
+ let comparison;
2720
+ if (includeCompare && previous) comparison = await compareCommitsCore({
2721
+ token,
2722
+ owner,
2723
+ repo,
2724
+ base: previous.tagName,
2725
+ head: release.tagName,
2726
+ includePatch: false
2727
+ });
2728
+ return {
2729
+ release,
2730
+ ...previous !== void 0 ? { previousRelease: previous } : {},
2731
+ ...comparison !== void 0 ? { comparison } : {}
2732
+ };
2733
+ }
2734
+ const getCiFailureContextInputSchema = z.object({
2735
+ owner: z.string().describe("Repository owner"),
2736
+ repo: z.string().describe("Repository name"),
2737
+ ref: z.string().describe("Branch, tag, or commit SHA to inspect"),
2738
+ maxFailedRuns: z.number().optional().default(5).describe("Max recent failed workflow runs to include"),
2739
+ maxFailedJobs: z.number().optional().default(10).describe("Max failed jobs (with failed steps) from the latest failed run")
2740
+ });
2741
+ const getCiFailureContextDescription = "Diagnose CI failures for a ref in one call — combined status, failing check runs, recent failed workflow runs, and failed jobs/steps from the latest failure";
2742
+ const FAILURE_CONCLUSIONS = /* @__PURE__ */ new Set([
2743
+ "failure",
2744
+ "timed_out",
2745
+ "action_required",
2746
+ "cancelled",
2747
+ "startup_failure"
2748
+ ]);
2749
+ async function getCiFailureContextCore({ token, owner, repo, ref, maxFailedRuns, maxFailedJobs }) {
2750
+ const [combinedStatus, checkRunsResult, failedRuns] = await Promise.all([
2751
+ getCombinedStatusCore({
2752
+ token,
2753
+ owner,
2754
+ repo,
2755
+ ref
2756
+ }),
2757
+ listCheckRunsCore({
2758
+ token,
2759
+ owner,
2760
+ repo,
2761
+ ref,
2762
+ perPage: 100,
2763
+ maxPages: 1
2764
+ }),
2765
+ listWorkflowRunsCore({
2766
+ token,
2767
+ owner,
2768
+ repo,
2769
+ branch: ref,
2770
+ status: "failure",
2771
+ perPage: maxFailedRuns,
2772
+ page: 1,
2773
+ maxPages: 1
2774
+ })
2775
+ ]);
2776
+ const failedCheckRuns = checkRunsResult.checkRuns.filter((run) => run.conclusion != null && FAILURE_CONCLUSIONS.has(run.conclusion));
2777
+ const latestFailedRun = failedRuns.runs[0];
2778
+ let latestFailure;
2779
+ if (latestFailedRun) latestFailure = {
2780
+ run: latestFailedRun,
2781
+ jobs: (await listWorkflowJobsCore({
2782
+ token,
2783
+ owner,
2784
+ repo,
2785
+ runId: latestFailedRun.id,
2786
+ filter: "latest",
2787
+ perPage: 100,
2788
+ page: 1
2789
+ })).jobs.filter((job) => job.conclusion != null && FAILURE_CONCLUSIONS.has(job.conclusion)).slice(0, maxFailedJobs).map((job) => ({
2790
+ id: job.id,
2791
+ name: job.name,
2792
+ status: job.status,
2793
+ conclusion: job.conclusion,
2794
+ url: job.url,
2795
+ startedAt: job.startedAt,
2796
+ completedAt: job.completedAt,
2797
+ steps: job.steps?.filter((step) => step.conclusion != null && FAILURE_CONCLUSIONS.has(step.conclusion))
2798
+ }))
2799
+ };
2800
+ return {
2801
+ ref,
2802
+ combinedStatus,
2803
+ failedCheckRuns,
2804
+ checkRunTotalCount: checkRunsResult.totalCount,
2805
+ recentFailedRuns: failedRuns.runs,
2806
+ ...latestFailure !== void 0 ? { latestFailure } : {}
2807
+ };
2808
+ }
2809
+ //#endregion
2810
+ //#region src/core/context.ts
2811
+ const CONTEXT_KEYS = [
2812
+ "owner",
2813
+ "repo",
2814
+ "pullNumber",
2815
+ "issueNumber",
2816
+ "ref"
2817
+ ];
2818
+ function hasContextValues(context) {
2819
+ return CONTEXT_KEYS.some((key) => context[key] !== void 0);
2820
+ }
2821
+ /**
2822
+ * Format a short system-prompt block describing the working context.
2823
+ * Returns an empty string when no context fields are set.
2824
+ */
2825
+ function formatContextInstructions(context) {
2826
+ if (!hasContextValues(context)) return "";
2827
+ const parts = [];
2828
+ if (context.owner && context.repo) parts.push(`repository ${context.owner}/${context.repo}`);
2829
+ else if (context.owner) parts.push(`owner ${context.owner}`);
2830
+ else if (context.repo) parts.push(`repository ${context.repo}`);
2831
+ if (context.pullNumber != null) parts.push(`pull request #${context.pullNumber}`);
2832
+ if (context.issueNumber != null) parts.push(`issue #${context.issueNumber}`);
2833
+ if (context.ref) parts.push(`ref ${context.ref}`);
2834
+ return `Working context: ${parts.join(", ")}. Prefer these values when calling tools — omit owner, repo, pullNumber, issueNumber, or ref when they match this context.`;
2835
+ }
2836
+ /**
2837
+ * Fill missing context fields on tool args from {@link GithubToolsContext}.
2838
+ * Explicit args always win over context defaults.
2839
+ */
2840
+ function mergeContextArgs(args, context) {
2841
+ const merged = { ...args };
2842
+ for (const key of CONTEXT_KEYS) if (merged[key] === void 0 && context[key] !== void 0) merged[key] = context[key];
2843
+ return merged;
2844
+ }
2845
+ function withContextDefault(field, value) {
2846
+ if (field instanceof z.ZodDefault) return withContextDefault(field.def.innerType, value);
2847
+ if (field instanceof z.ZodOptional) return withContextDefault(field.unwrap(), value);
2848
+ return field.default(value);
2849
+ }
2850
+ /**
2851
+ * Soften matching context fields on a Zod object schema so the model may omit them.
2852
+ * Fields present in `context` get a Zod `.default(value)`.
2853
+ */
2854
+ function softenContextSchema(schema, context) {
2855
+ if (!(schema instanceof z.ZodObject)) return schema;
2856
+ const shape = schema.shape;
2857
+ let changed = false;
2858
+ const nextShape = { ...shape };
2859
+ for (const key of CONTEXT_KEYS) {
2860
+ const value = context[key];
2861
+ if (value === void 0 || !(key in shape)) continue;
2862
+ nextShape[key] = withContextDefault(shape[key], value);
2863
+ changed = true;
2864
+ }
2865
+ return changed ? z.object(nextShape) : schema;
2866
+ }
2867
+ /**
2868
+ * Bind {@link GithubToolsContext} defaults onto a tool: softens matching input
2869
+ * fields and merges context into execute args when the model omits them.
2870
+ */
2871
+ function bindToolContext(tool, context) {
2872
+ if (!hasContextValues(context) || !tool.inputSchema) return tool;
2873
+ const inputSchema = softenContextSchema(tool.inputSchema, context);
2874
+ const originalExecute = tool.execute;
2875
+ if (!originalExecute) return {
2876
+ ...tool,
2877
+ inputSchema
2878
+ };
2879
+ return {
2880
+ ...tool,
2881
+ inputSchema,
2882
+ execute: async (args, options) => originalExecute(mergeContextArgs(args, context), options)
2883
+ };
2884
+ }
2885
+ /**
2886
+ * Apply {@link GithubToolsContext} to every tool in a set.
2887
+ */
2888
+ function bindToolsContext(tools, context) {
2889
+ if (!context || !hasContextValues(context)) return tools;
2890
+ const bound = {};
2891
+ for (const [name, tool] of Object.entries(tools)) bound[name] = bindToolContext(tool, context);
2892
+ return bound;
2893
+ }
2894
+ //#endregion
2895
+ //#region src/core/presets.ts
2896
+ /**
2897
+ * Predefined tool presets for common use cases.
2898
+ * Pass to {@link createGithubTools}, {@link createGithubAgent}, or {@link createDurableGithubAgent}.
2899
+ * Presets can be combined by passing an array.
2900
+ */
2901
+ const PRESET_TOOLS = {
2902
+ /**
2903
+ * **Code review** — review pull requests and submit feedback.
2904
+ *
2905
+ * Tools: `getPullRequest`, `listPullRequests`, `listPullRequestFiles`, `listPullRequestReviews`, `getPullRequestContext`,
2906
+ * `getFileContent`, `listCommits`, `getCommit`, `getBlame`, `compareCommits`, `getRepository`, `listBranches`,
2907
+ * `searchCode`, `listCheckRuns`, `getCombinedStatus`, `updatePullRequest`, `addPullRequestComment`, `updatePullRequestComment`,
2908
+ * `deletePullRequestComment`, `createPullRequestReview`, `requestReviewers`.
2909
+ *
2910
+ * Agent prompt: optimized for thorough PR review with inline feedback.
2911
+ */
2912
+ "code-review": [
2913
+ "getPullRequest",
2914
+ "listPullRequests",
2915
+ "listPullRequestFiles",
2916
+ "listPullRequestReviews",
2917
+ "getPullRequestContext",
2918
+ "getFileContent",
2919
+ "listCommits",
2920
+ "getCommit",
2921
+ "getBlame",
2922
+ "compareCommits",
2923
+ "getRepository",
2924
+ "listBranches",
2925
+ "searchCode",
2926
+ "listCheckRuns",
2927
+ "getCombinedStatus",
2928
+ "updatePullRequest",
2929
+ "addPullRequestComment",
2930
+ "updatePullRequestComment",
2931
+ "deletePullRequestComment",
2932
+ "createPullRequestReview",
2933
+ "requestReviewers"
2934
+ ],
2935
+ /**
2936
+ * **Issue triage** — manage and organize GitHub issues.
2937
+ *
2938
+ * Tools: `listIssues`, `getIssueContext`, `createIssue`, `addIssueComment`, `updateIssueComment`, `deleteIssueComment`,
2939
+ * `closeIssue`, `updateIssue`, `addLabels`, `removeLabel`, `addAssignees`, `removeAssignees`,
2940
+ * `listIssueReactions`, `addIssueReaction`, `listCommentReactions`, `addCommentReaction`, `getRepository`,
2941
+ * `searchRepositories`, `searchCode`, `searchIssues`.
2942
+ *
2943
+ * Prefer `getIssueContext` (issue + `labelNames` + recent comments) over separate get/list calls.
2944
+ * Reopen a closed issue with `updateIssue` (`state: 'open'`) — there is no separate reopen tool.
2945
+ * Acknowledge a report with `addIssueReaction` / `addCommentReaction` instead of a comment when no reply is needed.
2946
+ * Agent prompt: optimized for categorizing, labeling, and responding to issues.
2947
+ */
2948
+ "issue-triage": [
2949
+ "listIssues",
2950
+ "getIssueContext",
2951
+ "createIssue",
2952
+ "addIssueComment",
2953
+ "updateIssueComment",
2954
+ "deleteIssueComment",
2955
+ "closeIssue",
2956
+ "updateIssue",
2957
+ "addLabels",
2958
+ "removeLabel",
2959
+ "addAssignees",
2960
+ "removeAssignees",
2961
+ "listIssueReactions",
2962
+ "addIssueReaction",
2963
+ "listCommentReactions",
2964
+ "addCommentReaction",
2965
+ "getRepository",
2966
+ "searchRepositories",
2967
+ "searchCode",
2968
+ "searchIssues"
2969
+ ],
2970
+ /**
2971
+ * **CI operations** — monitor and manage GitHub Actions workflows.
2972
+ *
2973
+ * Tools: `getRepository`, `listBranches`, `listCommits`, `getCommit`,
2974
+ * `listWorkflows`, `listWorkflowRuns`, `getWorkflowRun`, `listWorkflowJobs`, `listCheckRuns`, `getCombinedStatus`, `getCiFailureContext`,
2975
+ * `triggerWorkflow`, `cancelWorkflowRun`, `rerunWorkflowRun`.
2976
+ *
2977
+ * Agent prompt: optimized for diagnosing CI failures and managing workflow runs.
2978
+ */
2979
+ "ci-ops": [
2980
+ "getRepository",
2981
+ "listBranches",
2982
+ "listCommits",
2983
+ "getCommit",
2984
+ "listWorkflows",
2985
+ "listWorkflowRuns",
2986
+ "getWorkflowRun",
2987
+ "listWorkflowJobs",
2988
+ "listCheckRuns",
2989
+ "getCombinedStatus",
2990
+ "getCiFailureContext",
2991
+ "triggerWorkflow",
2992
+ "cancelWorkflowRun",
2993
+ "rerunWorkflowRun"
2994
+ ],
2995
+ /**
2996
+ * **Repository explorer** — read-only access to browse codebases.
2997
+ *
2998
+ * Tools: all read-only tools including repos, branches, PRs, issues, discussions, commits, blame, comparisons,
2999
+ * search, gists, workflows, checks, and releases. No write operations.
3000
+ *
3001
+ * Agent prompt: optimized for answering questions about code structure and history.
3002
+ */
3003
+ "repo-explorer": [
3004
+ "getRepository",
3005
+ "listBranches",
3006
+ "getFileContent",
3007
+ "getRepositoryTree",
3008
+ "listPullRequests",
3009
+ "getPullRequest",
3010
+ "listPullRequestFiles",
3011
+ "listPullRequestReviews",
3012
+ "getPullRequestContext",
3013
+ "listIssues",
3014
+ "getIssue",
3015
+ "getIssueContext",
3016
+ "listDiscussions",
3017
+ "getDiscussion",
3018
+ "listLabels",
3019
+ "listCommits",
3020
+ "getCommit",
3021
+ "getBlame",
3022
+ "compareCommits",
3023
+ "searchCode",
3024
+ "searchRepositories",
3025
+ "searchIssues",
3026
+ "listGists",
3027
+ "getGist",
3028
+ "listGistComments",
3029
+ "listWorkflows",
3030
+ "listWorkflowRuns",
3031
+ "getWorkflowRun",
3032
+ "listWorkflowJobs",
3033
+ "listCheckRuns",
3034
+ "getCombinedStatus",
3035
+ "getCiFailureContext",
3036
+ "listReleases",
3037
+ "getLatestRelease",
3038
+ "getRelease",
3039
+ "getReleaseContext"
3040
+ ],
3041
+ /**
3042
+ * **Security audit** — review repositories for security risks and report findings.
3043
+ *
3044
+ * Tools: read-only exploration (`getFileContent`, `getRepositoryTree`, `searchCode`, `searchIssues`, `listCommits`, `getCommit`,
3045
+ * `getBlame`, `compareCommits`), PR and CI visibility (`listPullRequests`, `getPullRequest`, `listPullRequestFiles`,
3046
+ * `getPullRequestContext`, `listCheckRuns`, `getCombinedStatus`, `getCiFailureContext`, `listWorkflows`, `listWorkflowRuns`,
3047
+ * `getWorkflowRun`, `listWorkflowJobs`), plus `createIssue`, `addIssueComment`, and `addLabels` to report findings.
3048
+ * No destructive writes.
3049
+ *
3050
+ * Agent prompt: optimized for finding and reporting security risks without making changes.
3051
+ */
3052
+ "security-audit": [
3053
+ "getRepository",
3054
+ "listBranches",
3055
+ "getFileContent",
3056
+ "getRepositoryTree",
3057
+ "listCommits",
3058
+ "getCommit",
3059
+ "getBlame",
3060
+ "compareCommits",
3061
+ "searchCode",
3062
+ "searchRepositories",
3063
+ "searchIssues",
3064
+ "listPullRequests",
3065
+ "getPullRequest",
3066
+ "listPullRequestFiles",
3067
+ "getPullRequestContext",
3068
+ "listCheckRuns",
3069
+ "getCombinedStatus",
3070
+ "getCiFailureContext",
3071
+ "listWorkflows",
3072
+ "listWorkflowRuns",
3073
+ "getWorkflowRun",
3074
+ "listWorkflowJobs",
3075
+ "listIssues",
3076
+ "getIssue",
3077
+ "getIssueContext",
3078
+ "createIssue",
3079
+ "addIssueComment",
3080
+ "addLabels"
3081
+ ],
3082
+ /**
3083
+ * **Release manager** — prepare and publish GitHub releases.
3084
+ *
3085
+ * Tools: `getRepository`, `listBranches`, `listCommits`, `getCommit`, `compareCommits`,
3086
+ * `listReleases`, `getLatestRelease`, `getRelease`, `getReleaseContext`, `createRelease`, `updateRelease`, `deleteRelease`,
3087
+ * `listWorkflows`, `listWorkflowRuns`, `getWorkflowRun`, `listWorkflowJobs`, `triggerWorkflow`,
3088
+ * `listPullRequests`, `getPullRequest`.
3089
+ *
3090
+ * Agent prompt: optimized for summarizing changes and cutting releases safely.
3091
+ */
3092
+ "release-manager": [
3093
+ "getRepository",
3094
+ "listBranches",
3095
+ "listCommits",
3096
+ "getCommit",
3097
+ "compareCommits",
3098
+ "listReleases",
3099
+ "getLatestRelease",
3100
+ "getRelease",
3101
+ "getReleaseContext",
3102
+ "createRelease",
3103
+ "updateRelease",
3104
+ "deleteRelease",
3105
+ "listWorkflows",
3106
+ "listWorkflowRuns",
3107
+ "getWorkflowRun",
3108
+ "listWorkflowJobs",
3109
+ "triggerWorkflow",
3110
+ "listPullRequests",
3111
+ "getPullRequest"
3112
+ ],
3113
+ /**
3114
+ * **Discussion moderator** — answer and moderate repository Discussions.
3115
+ *
3116
+ * Tools: `listDiscussions`, `getDiscussion`, `addDiscussionComment`,
3117
+ * `getRepository`, `searchIssues`, `getIssueContext`, `addIssueComment`.
3118
+ *
3119
+ * Prefer discussions for Q&A; link related issues with `getIssueContext` / `addIssueComment` when needed.
3120
+ * Agent prompt: optimized for clear, on-topic discussion replies.
3121
+ */
3122
+ "discussion-moderator": [
3123
+ "listDiscussions",
3124
+ "getDiscussion",
3125
+ "addDiscussionComment",
3126
+ "getRepository",
3127
+ "searchIssues",
3128
+ "getIssueContext",
3129
+ "addIssueComment"
3130
+ ],
3131
+ /**
3132
+ * **Notification inbox** — triage authenticated-user notification threads.
3133
+ *
3134
+ * Tools: `listNotifications`, `markNotificationRead`, `getIssue`, `getPullRequest`, `getRepository`.
3135
+ *
3136
+ * Requires a user PAT with the Notifications account permission — not available on Connect installation tokens.
3137
+ * Agent prompt: optimized for clearing inbox noise and following up on actionable threads.
3138
+ */
3139
+ "notification-inbox": [
3140
+ "listNotifications",
3141
+ "markNotificationRead",
3142
+ "getIssue",
3143
+ "getPullRequest",
3144
+ "getRepository"
3145
+ ],
3146
+ /**
3147
+ * **PR author** — open pull requests without the full write surface.
3148
+ *
3149
+ * Tools: `getRepository`, `listBranches`, `getFileContent`, `createBranch`, `createOrUpdateFile`,
3150
+ * `createPullRequest`, `updatePullRequest`, `getPullRequest`, `listPullRequestFiles`,
3151
+ * `compareCommits`, `getCommit`.
3152
+ *
3153
+ * Agent prompt: optimized for branching, editing files, and opening focused PRs.
3154
+ */
3155
+ "pr-author": [
3156
+ "getRepository",
3157
+ "listBranches",
3158
+ "getFileContent",
3159
+ "createBranch",
3160
+ "createOrUpdateFile",
3161
+ "createPullRequest",
3162
+ "updatePullRequest",
3163
+ "getPullRequest",
3164
+ "listPullRequestFiles",
3165
+ "compareCommits",
3166
+ "getCommit"
3167
+ ],
3168
+ /**
3169
+ * **Maintainer** — full repository maintenance with all read and write tools.
3170
+ *
3171
+ * Tools: all tools (same as omitting `preset`).
3172
+ *
3173
+ * Agent prompt: optimized for day-to-day repo maintenance with careful write operations.
3174
+ */
3175
+ "maintainer": [
3176
+ "getRepository",
3177
+ "listBranches",
3178
+ "getFileContent",
3179
+ "getRepositoryTree",
3180
+ "createBranch",
3181
+ "forkRepository",
3182
+ "createRepository",
3183
+ "createOrUpdateFile",
3184
+ "listPullRequests",
3185
+ "getPullRequest",
3186
+ "listPullRequestFiles",
3187
+ "listPullRequestReviews",
3188
+ "getPullRequestContext",
3189
+ "createPullRequest",
3190
+ "mergePullRequest",
3191
+ "updatePullRequest",
3192
+ "addPullRequestComment",
3193
+ "updatePullRequestComment",
3194
+ "deletePullRequestComment",
3195
+ "createPullRequestReview",
3196
+ "requestReviewers",
3197
+ "listIssues",
3198
+ "getIssue",
3199
+ "getIssueContext",
3200
+ "createIssue",
3201
+ "addIssueComment",
3202
+ "updateIssueComment",
3203
+ "deleteIssueComment",
3204
+ "closeIssue",
3205
+ "updateIssue",
3206
+ "listLabels",
3207
+ "addLabels",
3208
+ "removeLabel",
3209
+ "addAssignees",
3210
+ "removeAssignees",
3211
+ "listIssueReactions",
3212
+ "addIssueReaction",
3213
+ "listCommentReactions",
3214
+ "addCommentReaction",
3215
+ "listDiscussions",
3216
+ "getDiscussion",
3217
+ "addDiscussionComment",
3218
+ "listNotifications",
3219
+ "markNotificationRead",
3220
+ "listCommits",
3221
+ "getCommit",
3222
+ "getBlame",
3223
+ "compareCommits",
3224
+ "searchCode",
3225
+ "searchRepositories",
3226
+ "searchIssues",
3227
+ "listGists",
3228
+ "getGist",
3229
+ "listGistComments",
3230
+ "createGist",
3231
+ "updateGist",
3232
+ "deleteGist",
3233
+ "createGistComment",
3234
+ "listWorkflows",
3235
+ "listWorkflowRuns",
3236
+ "getWorkflowRun",
3237
+ "listWorkflowJobs",
3238
+ "triggerWorkflow",
3239
+ "cancelWorkflowRun",
3240
+ "rerunWorkflowRun",
3241
+ "listCheckRuns",
3242
+ "getCombinedStatus",
3243
+ "getCiFailureContext",
3244
+ "listReleases",
3245
+ "getLatestRelease",
3246
+ "getRelease",
3247
+ "getReleaseContext",
3248
+ "createRelease",
3249
+ "updateRelease",
3250
+ "deleteRelease"
3251
+ ]
3252
+ };
3253
+ /**
3254
+ * Resolve a preset (or array of presets) into the set of tool names it includes.
3255
+ *
3256
+ * @param preset - A single preset or array of presets to combine.
3257
+ * @returns A `Set` of tool names, or `null` when `preset` is falsy.
3258
+ */
3259
+ function resolvePresetTools(preset) {
3260
+ if (!preset) return null;
3261
+ const presets = Array.isArray(preset) ? preset : [preset];
3262
+ const tools = /* @__PURE__ */ new Set();
3263
+ for (const p of presets) for (const t of PRESET_TOOLS[p]) tools.add(t);
3264
+ return tools;
3265
+ }
3266
+ //#endregion
3267
+ //#region src/core/tool-names.ts
3268
+ /**
3269
+ * All GitHub tool names available via {@link createGithubTools}.
3270
+ * Each key maps to its own string literal for IDE autocomplete and hover docs.
3271
+ */
3272
+ const GITHUB_TOOL_NAMES = {
3273
+ /** Get information about a GitHub repository including description, stars, forks, language, and default branch. */
3274
+ getRepository: "getRepository",
3275
+ /** List branches in a GitHub repository. */
3276
+ listBranches: "listBranches",
3277
+ /** Get the content of a file from a GitHub repository. Prefer startLine/endLine or maxLines for large files. */
3278
+ getFileContent: "getFileContent",
3279
+ /** List the file and directory structure of a repository at a given ref. */
3280
+ getRepositoryTree: "getRepositoryTree",
3281
+ /** Create a new branch in a GitHub repository from an existing branch or commit SHA. Requires approval by default. */
3282
+ createBranch: "createBranch",
3283
+ /** Fork a GitHub repository to the authenticated user account or a specified organization. Requires approval by default. */
3284
+ forkRepository: "forkRepository",
3285
+ /** Create a new GitHub repository for the authenticated user or a specified organization. Requires approval by default. */
3286
+ createRepository: "createRepository",
3287
+ /** Create or update a file in a GitHub repository. Provide the SHA when updating an existing file. Requires approval by default. */
3288
+ createOrUpdateFile: "createOrUpdateFile",
3289
+ /** List pull requests for a GitHub repository. */
3290
+ listPullRequests: "listPullRequests",
3291
+ /** Get detailed information about a specific pull request. Body truncated by default (detail: summary). */
3292
+ getPullRequest: "getPullRequest",
3293
+ /** Create a new pull request in a GitHub repository. Requires approval by default. */
3294
+ createPullRequest: "createPullRequest",
3295
+ /** Merge a pull request. Requires approval by default. */
3296
+ mergePullRequest: "mergePullRequest",
3297
+ /** Update a pull request — title, body, state, base branch, or draft status. Requires approval by default. */
3298
+ updatePullRequest: "updatePullRequest",
3299
+ /** Add a comment to a pull request. Requires approval by default. */
3300
+ addPullRequestComment: "addPullRequestComment",
3301
+ /** Update the body of a comment on a pull request. Requires approval by default. */
3302
+ updatePullRequestComment: "updatePullRequestComment",
3303
+ /** Delete a comment from a pull request permanently. Requires approval by default. */
3304
+ deletePullRequestComment: "deletePullRequestComment",
3305
+ /** List files changed in a pull request with status and stats. Patches omitted by default — set includePatch true for diffs. */
3306
+ listPullRequestFiles: "listPullRequestFiles",
3307
+ /** List reviews on a pull request (approvals, change requests, and comments). */
3308
+ listPullRequestReviews: "listPullRequestReviews",
3309
+ /** Submit a pull request review — approve, request changes, or comment with optional inline comments on specific lines. Requires approval by default. */
3310
+ createPullRequestReview: "createPullRequestReview",
3311
+ /** Request reviews from users or teams on a pull request. Requires approval by default. */
3312
+ requestReviewers: "requestReviewers",
3313
+ /** Fetch pull request details plus files, reviews, and optional CI checks in one call. */
3314
+ getPullRequestContext: "getPullRequestContext",
3315
+ /** List issues for a GitHub repository (excludes pull requests). */
3316
+ listIssues: "listIssues",
3317
+ /** Get detailed information about a specific issue. Body truncated by default (detail: summary). */
3318
+ getIssue: "getIssue",
3319
+ /** Fetch an issue plus available label names and recent comments in one call. */
3320
+ getIssueContext: "getIssueContext",
3321
+ /** Create a new issue in a GitHub repository. Requires approval by default. */
3322
+ createIssue: "createIssue",
3323
+ /** Add a comment to a GitHub issue. Requires approval by default. */
3324
+ addIssueComment: "addIssueComment",
3325
+ /** Update the body of a comment on a GitHub issue. Requires approval by default. */
3326
+ updateIssueComment: "updateIssueComment",
3327
+ /** Delete a comment from a GitHub issue permanently. Requires approval by default. */
3328
+ deleteIssueComment: "deleteIssueComment",
3329
+ /** Close an open GitHub issue. Requires approval by default. */
3330
+ closeIssue: "closeIssue",
3331
+ /** Update a GitHub issue — title, body, state, labels, milestone, or assignees. Requires approval by default. */
3332
+ updateIssue: "updateIssue",
3333
+ /** List labels available in a GitHub repository. */
3334
+ listLabels: "listLabels",
3335
+ /** Add labels to an issue or pull request. Requires approval by default. */
3336
+ addLabels: "addLabels",
3337
+ /** Remove a label from an issue or pull request. Requires approval by default. */
3338
+ removeLabel: "removeLabel",
3339
+ /** Assign users to an issue or pull request. Requires approval by default. */
3340
+ addAssignees: "addAssignees",
3341
+ /** Remove assignees from an issue or pull request. Requires approval by default. */
3342
+ removeAssignees: "removeAssignees",
3343
+ /** Search for code in GitHub repositories. Use qualifiers like "repo:owner/name" to scope the search. Results include matching text snippets when GitHub returns them. */
3344
+ searchCode: "searchCode",
3345
+ /** Search for GitHub repositories by keyword, topic, language, or other qualifiers. */
3346
+ searchRepositories: "searchRepositories",
3347
+ /** Search for issues and pull requests across GitHub using search qualifiers like "repo:owner/name is:open". */
3348
+ searchIssues: "searchIssues",
3349
+ /** List commits for a GitHub repository. Filter by file path to see commits that touched a file. For line-by-line attribution at a given ref, use getBlame instead. */
3350
+ listCommits: "listCommits",
3351
+ /** Get detailed information about a specific commit, including the list of files changed. Patches omitted by default. */
3352
+ getCommit: "getCommit",
3353
+ /** Line-level git blame for a file at a commit-like ref (branch, tag, or SHA). Returns contiguous ranges mapping lines to the commits that last modified them. */
3354
+ getBlame: "getBlame",
3355
+ /** Compare two branches, tags, or commits — ahead/behind counts, commits in between, and differing files. Patches omitted by default. */
3356
+ compareCommits: "compareCommits",
3357
+ /** List gists for the authenticated user or a specific user. */
3358
+ listGists: "listGists",
3359
+ /** Get a gist by ID, including file contents. */
3360
+ getGist: "getGist",
3361
+ /** List comments on a gist. */
3362
+ listGistComments: "listGistComments",
3363
+ /** Create a new gist with one or more files. Requires approval by default. */
3364
+ createGist: "createGist",
3365
+ /** Update an existing gist — edit description, update files, or remove files. Requires approval by default. */
3366
+ updateGist: "updateGist",
3367
+ /** Delete a gist permanently. Requires approval by default. */
3368
+ deleteGist: "deleteGist",
3369
+ /** Add a comment to a gist. Requires approval by default. */
3370
+ createGistComment: "createGistComment",
3371
+ /** List GitHub Actions workflows in a repository. */
3372
+ listWorkflows: "listWorkflows",
3373
+ /** List workflow runs for a repository, optionally filtered by workflow, branch, status, or event. */
3374
+ listWorkflowRuns: "listWorkflowRuns",
3375
+ /** Get details of a specific workflow run including status, timing, and trigger info. */
3376
+ getWorkflowRun: "getWorkflowRun",
3377
+ /** List jobs for a workflow run, including step-level status and timing. */
3378
+ listWorkflowJobs: "listWorkflowJobs",
3379
+ /** Trigger a workflow via workflow_dispatch event. Requires approval by default. */
3380
+ triggerWorkflow: "triggerWorkflow",
3381
+ /** Cancel an in-progress workflow run. Requires approval by default. */
3382
+ cancelWorkflowRun: "cancelWorkflowRun",
3383
+ /** Re-run a workflow run, optionally only the failed jobs. Requires approval by default. */
3384
+ rerunWorkflowRun: "rerunWorkflowRun",
3385
+ /** List check runs (Checks API — GitHub Actions and other CI providers) for a commit, branch, or tag. */
3386
+ listCheckRuns: "listCheckRuns",
3387
+ /** Get the combined commit status (Statuses API — legacy CI integrations) for a commit, branch, or tag. */
3388
+ getCombinedStatus: "getCombinedStatus",
3389
+ /** Diagnose CI failures for a ref — combined status, failing checks, and failed workflow jobs in one call. */
3390
+ getCiFailureContext: "getCiFailureContext",
3391
+ /** List discussions in a GitHub repository, most recently updated first, optionally filtered by category. */
3392
+ listDiscussions: "listDiscussions",
3393
+ /** Get a GitHub discussion by number. Body truncated by default (detail: summary). */
3394
+ getDiscussion: "getDiscussion",
3395
+ /** Add a comment to a GitHub discussion. Requires approval by default. */
3396
+ addDiscussionComment: "addDiscussionComment",
3397
+ /** List notification threads for the authenticated user. Requires a token with notifications access. */
3398
+ listNotifications: "listNotifications",
3399
+ /** Mark a single notification thread as read. Requires approval by default. */
3400
+ markNotificationRead: "markNotificationRead",
3401
+ /** List reactions on an issue or pull request conversation, with per-emoji counts. */
3402
+ listIssueReactions: "listIssueReactions",
3403
+ /** React to an issue or pull request with an emoji. Requires approval by default. */
3404
+ addIssueReaction: "addIssueReaction",
3405
+ /** List reactions on an issue or pull request comment, with per-emoji counts. */
3406
+ listCommentReactions: "listCommentReactions",
3407
+ /** React to an issue or pull request comment with an emoji. Requires approval by default. */
3408
+ addCommentReaction: "addCommentReaction",
3409
+ /** List releases for a GitHub repository, newest first (includes drafts and prereleases). */
3410
+ listReleases: "listReleases",
3411
+ /** Get the latest published release for a GitHub repository (excludes drafts and prereleases). Body truncated by default. */
3412
+ getLatestRelease: "getLatestRelease",
3413
+ /** Get a specific release by ID, including its assets. Body truncated by default. */
3414
+ getRelease: "getRelease",
3415
+ /** Fetch a release plus the previous release and tag comparison in one call. */
3416
+ getReleaseContext: "getReleaseContext",
3417
+ /** Create a new release (and its tag if needed) in a GitHub repository. Requires approval by default. */
3418
+ createRelease: "createRelease",
3419
+ /** Update an existing release — tag, target, title, notes, draft, or prerelease status. Requires approval by default. */
3420
+ updateRelease: "updateRelease",
3421
+ /** Delete a release permanently. Requires approval by default. */
3422
+ deleteRelease: "deleteRelease"
3423
+ };
3424
+ const ALL_GITHUB_TOOL_NAMES = Object.values(GITHUB_TOOL_NAMES);
3425
+ //#endregion
3426
+ //#region src/core/write-tools.ts
3427
+ /**
3428
+ * Write tools that mutate GitHub state. All require user approval by default
3429
+ * unless overridden via {@link ApprovalConfig}.
3430
+ */
3431
+ const GITHUB_WRITE_TOOLS = {
3432
+ /** Create a new branch in a GitHub repository from an existing branch or commit SHA. Requires approval by default. */
3433
+ createBranch: "createBranch",
3434
+ /** Fork a GitHub repository to the authenticated user account or a specified organization. Requires approval by default. */
3435
+ forkRepository: "forkRepository",
3436
+ /** Create a new GitHub repository for the authenticated user or a specified organization. Requires approval by default. */
3437
+ createRepository: "createRepository",
3438
+ /** Create or update a file in a GitHub repository. Requires approval by default. */
3439
+ createOrUpdateFile: "createOrUpdateFile",
3440
+ /** Create a new pull request in a GitHub repository. Requires approval by default. */
3441
+ createPullRequest: "createPullRequest",
3442
+ /** Merge a pull request. Requires approval by default. */
3443
+ mergePullRequest: "mergePullRequest",
3444
+ /** Update a pull request. Requires approval by default. */
3445
+ updatePullRequest: "updatePullRequest",
3446
+ /** Add a comment to a pull request. Requires approval by default. */
3447
+ addPullRequestComment: "addPullRequestComment",
3448
+ /** Update a pull request comment. Requires approval by default. */
3449
+ updatePullRequestComment: "updatePullRequestComment",
3450
+ /** Delete a pull request comment. Requires approval by default. */
3451
+ deletePullRequestComment: "deletePullRequestComment",
3452
+ /** Submit a pull request review with optional inline comments. Requires approval by default. */
3453
+ createPullRequestReview: "createPullRequestReview",
3454
+ /** Request reviews from users or teams on a pull request. Requires approval by default. */
3455
+ requestReviewers: "requestReviewers",
3456
+ /** Create a new issue in a GitHub repository. Requires approval by default. */
3457
+ createIssue: "createIssue",
3458
+ /** Add a comment to a GitHub issue. Requires approval by default. */
3459
+ addIssueComment: "addIssueComment",
3460
+ /** Update a GitHub issue comment. Requires approval by default. */
3461
+ updateIssueComment: "updateIssueComment",
3462
+ /** Delete a GitHub issue comment. Requires approval by default. */
3463
+ deleteIssueComment: "deleteIssueComment",
3464
+ /** Close an open GitHub issue. Requires approval by default. */
3465
+ closeIssue: "closeIssue",
3466
+ /** Update a GitHub issue. Requires approval by default. */
3467
+ updateIssue: "updateIssue",
3468
+ /** Add labels to an issue or pull request. Requires approval by default. */
3469
+ addLabels: "addLabels",
3470
+ /** Remove a label from an issue or pull request. Requires approval by default. */
3471
+ removeLabel: "removeLabel",
3472
+ /** Assign users to an issue or pull request. Requires approval by default. */
3473
+ addAssignees: "addAssignees",
3474
+ /** Remove assignees from an issue or pull request. Requires approval by default. */
3475
+ removeAssignees: "removeAssignees",
3476
+ /** Create a new gist with one or more files. Requires approval by default. */
3477
+ createGist: "createGist",
3478
+ /** Update an existing gist. Requires approval by default. */
3479
+ updateGist: "updateGist",
3480
+ /** Delete a gist permanently. Requires approval by default. */
3481
+ deleteGist: "deleteGist",
3482
+ /** Add a comment to a gist. Requires approval by default. */
3483
+ createGistComment: "createGistComment",
3484
+ /** Add a comment to a GitHub discussion. Requires approval by default. */
3485
+ addDiscussionComment: "addDiscussionComment",
3486
+ /** Mark a single notification thread as read. Requires approval by default. */
3487
+ markNotificationRead: "markNotificationRead",
3488
+ /** React to an issue or pull request with an emoji. Requires approval by default. */
3489
+ addIssueReaction: "addIssueReaction",
3490
+ /** React to an issue or pull request comment with an emoji. Requires approval by default. */
3491
+ addCommentReaction: "addCommentReaction",
3492
+ /** Trigger a workflow via workflow_dispatch event. Requires approval by default. */
3493
+ triggerWorkflow: "triggerWorkflow",
3494
+ /** Cancel an in-progress workflow run. Requires approval by default. */
3495
+ cancelWorkflowRun: "cancelWorkflowRun",
3496
+ /** Re-run a workflow run, optionally only the failed jobs. Requires approval by default. */
3497
+ rerunWorkflowRun: "rerunWorkflowRun",
3498
+ /** Create a new release (and its tag if needed) in a GitHub repository. Requires approval by default. */
3499
+ createRelease: "createRelease",
3500
+ /** Update an existing release. Requires approval by default. */
3501
+ updateRelease: "updateRelease",
3502
+ /** Delete a release permanently. Requires approval by default. */
3503
+ deleteRelease: "deleteRelease"
3504
+ };
3505
+ Object.values(GITHUB_WRITE_TOOLS);
3506
+ //#endregion
3507
+ export { listWorkflowJobsDescription as $, listLabelsDescription as $n, getFileContentToModelOutput as $r, searchRepositoriesDescription as $t, getLatestReleaseInputSchema as A, addAssigneesInputSchema as An, listPullRequestFilesInputSchema as Ar, listGistsInputSchema as At, getCombinedStatusCore as B, createIssueCore as Bn, requestReviewersCore as Br, getCommitCore as Bt, createReleaseDescription as C, listBranchesCore as Ci, listCommentReactionsDescription as Cn, deletePullRequestCommentDescription as Cr, getGistDescription as Ct, deleteReleaseInputSchema as D, listIssueReactionsInputSchema as Dn, getPullRequestInputSchema as Dr, listGistCommentsInputSchema as Dt, deleteReleaseDescription as E, createOctokit as Ei, listIssueReactionsDescription as En, getPullRequestDescription as Er, listGistCommentsDescription as Et, listReleasesDescription as F, addLabelsDescription as Fn, listPullRequestsDescription as Fr, compareCommitsDescription as Ft, listCheckRunsInputSchema as G, deleteIssueCommentInputSchema as Gn, updatePullRequestCommentInputSchema as Gr, listCommitsInputSchema as Gt, getCombinedStatusInputSchema as H, createIssueInputSchema as Hn, requestReviewersInputSchema as Hr, getCommitInputSchema as Ht, listReleasesInputSchema as I, addLabelsInputSchema as In, listPullRequestsInputSchema as Ir, compareCommitsInputSchema as It, cancelWorkflowRunInputSchema as J, getIssueInputSchema as Jn, updatePullRequestInputSchema as Jr, searchCodeInputSchema as Jt, cancelWorkflowRunCore as K, getIssueCore as Kn, updatePullRequestCore as Kr, searchCodeCore as Kt, updateReleaseCore as L, closeIssueCore as Ln, mergePullRequestCore as Lr, getBlameCore as Lt, getReleaseDescription as M, addIssueCommentDescription as Mn, listPullRequestReviewsDescription as Mr, updateGistDescription as Mt, getReleaseInputSchema as N, addIssueCommentInputSchema as Nn, listPullRequestReviewsInputSchema as Nr, updateGistInputSchema as Nt, getLatestReleaseCore as O, addAssigneesCore as On, listPullRequestFilesCore as Or, listGistsCore as Ot, listReleasesCore as P, addLabelsCore as Pn, listPullRequestsCore as Pr, compareCommitsCore as Pt, listWorkflowJobsCore as Q, listLabelsCore as Qn, getCommitToModelOutput as Qr, searchRepositoriesCore as Qt, updateReleaseDescription as R, closeIssueDescription as Rn, mergePullRequestDescription as Rr, getBlameDescription as Rt, createReleaseCore as S, getRepositoryTreeInputSchema as Si, listCommentReactionsCore as Sn, deletePullRequestCommentCore as Sr, getGistCore as St, deleteReleaseCore as T, listBranchesInputSchema as Ti, listIssueReactionsCore as Tn, getPullRequestCore as Tr, listGistCommentsCore as Tt, listCheckRunsCore as U, deleteIssueCommentCore as Un, updatePullRequestCommentCore as Ur, listCommitsCore as Ut, getCombinedStatusDescription as V, createIssueDescription as Vn, requestReviewersDescription as Vr, getCommitDescription as Vt, listCheckRunsDescription as W, deleteIssueCommentDescription as Wn, updatePullRequestCommentDescription as Wr, listCommitsDescription as Wt, getWorkflowRunDescription as X, listIssuesDescription as Xn, resolveGithubToken as Xr, searchIssuesDescription as Xt, getWorkflowRunCore as Y, listIssuesCore as Yn, createGithubTokenResolver as Yr, searchIssuesCore as Yt, getWorkflowRunInputSchema as Z, listIssuesInputSchema as Zn, compareCommitsToModelOutput as Zr, searchIssuesInputSchema as Zt, getPullRequestContextDescription as _, getRepositoryCore as _i, addCommentReactionDescription as _n, createPullRequestDescription as _r, createGistDescription as _t, resolvePresetTools as a, createOrUpdateFileCore as ai, markNotificationReadDescription as an, removeLabelDescription as ar, listWorkflowsDescription as at, getReleaseContextDescription as b, getRepositoryTreeCore as bi, addIssueReactionDescription as bn, createPullRequestReviewDescription as br, deleteGistDescription as bt, mergeContextArgs as c, createRepositoryCore as ci, addDiscussionCommentDescription as cn, updateIssueCommentDescription as cr, rerunWorkflowRunDescription as ct, getCiFailureContextDescription as d, forkRepositoryCore as di, getDiscussionDescription as dn, updateIssueDescription as dr, triggerWorkflowDescription as dt, getPullRequestContextToModelOutput as ei, searchRepositoriesInputSchema as en, listLabelsInputSchema as er, listWorkflowJobsInputSchema as et, getCiFailureContextInputSchema as f, forkRepositoryDescription as fi, getDiscussionInputSchema as fn, updateIssueInputSchema as fr, triggerWorkflowInputSchema as ft, getPullRequestContextCore as g, getFileContentInputSchema as gi, addCommentReactionCore as gn, createPullRequestCore as gr, createGistCore as gt, getIssueContextInputSchema as h, getFileContentDescription as hi, listDiscussionsInputSchema as hn, addPullRequestCommentInputSchema as hr, createGistCommentInputSchema as ht, PRESET_TOOLS as i, createBranchInputSchema as ii, markNotificationReadCore as in, removeLabelCore as ir, listWorkflowsCore as it, getReleaseCore as j, addIssueCommentCore as jn, listPullRequestReviewsCore as jr, updateGistCore as jt, getLatestReleaseDescription as k, addAssigneesDescription as kn, listPullRequestFilesDescription as kr, listGistsDescription as kt, softenContextSchema as l, createRepositoryDescription as li, addDiscussionCommentInputSchema as ln, updateIssueCommentInputSchema as lr, rerunWorkflowRunInputSchema as lt, getIssueContextDescription as m, getFileContentCore as mi, listDiscussionsDescription as mn, addPullRequestCommentDescription as mr, createGistCommentDescription as mt, ALL_GITHUB_TOOL_NAMES as n, createBranchCore as ni, listNotificationsDescription as nn, removeAssigneesDescription as nr, listWorkflowRunsDescription as nt, bindToolsContext as o, createOrUpdateFileDescription as oi, markNotificationReadInputSchema as on, removeLabelInputSchema as or, listWorkflowsInputSchema as ot, getIssueContextCore as p, forkRepositoryInputSchema as pi, listDiscussionsCore as pn, addPullRequestCommentCore as pr, createGistCommentCore as pt, cancelWorkflowRunDescription as q, getIssueDescription as qn, updatePullRequestDescription as qr, searchCodeDescription as qt, GITHUB_TOOL_NAMES as r, createBranchDescription as ri, listNotificationsInputSchema as rn, removeAssigneesInputSchema as rr, listWorkflowRunsInputSchema as rt, formatContextInstructions as s, createOrUpdateFileInputSchema as si, addDiscussionCommentCore as sn, updateIssueCommentCore as sr, rerunWorkflowRunCore as st, GITHUB_WRITE_TOOLS as t, listPullRequestFilesToModelOutput as ti, listNotificationsCore as tn, removeAssigneesCore as tr, listWorkflowRunsCore as tt, getCiFailureContextCore as u, createRepositoryInputSchema as ui, getDiscussionCore as un, updateIssueCore as ur, triggerWorkflowCore as ut, getPullRequestContextInputSchema as v, getRepositoryDescription as vi, addCommentReactionInputSchema as vn, createPullRequestInputSchema as vr, createGistInputSchema as vt, createReleaseInputSchema as w, listBranchesDescription as wi, listCommentReactionsInputSchema as wn, deletePullRequestCommentInputSchema as wr, getGistInputSchema as wt, getReleaseContextInputSchema as x, getRepositoryTreeDescription as xi, addIssueReactionInputSchema as xn, createPullRequestReviewInputSchema as xr, deleteGistInputSchema as xt, getReleaseContextCore as y, getRepositoryInputSchema as yi, addIssueReactionCore as yn, createPullRequestReviewCore as yr, deleteGistCore as yt, updateReleaseInputSchema as z, closeIssueInputSchema as zn, mergePullRequestInputSchema as zr, getBlameInputSchema as zt };
3508
+
3509
+ //# sourceMappingURL=write-tools-uIVfURVp.mjs.map