@cepharum/mcp-gitlab 0.0.0-stage → 0.1.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 (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/package.json +50 -5
  5. package/src/audit.js +185 -0
  6. package/src/cli.js +411 -0
  7. package/src/connect.js +335 -0
  8. package/src/consent.js +115 -0
  9. package/src/downloads.js +94 -0
  10. package/src/errors.js +13 -0
  11. package/src/git.js +94 -0
  12. package/src/gitlab/client.js +406 -0
  13. package/src/gitlab/diff.js +79 -0
  14. package/src/hosts.js +228 -0
  15. package/src/paths.js +71 -0
  16. package/src/permissions/catalog.js +75 -0
  17. package/src/permissions/policy.js +230 -0
  18. package/src/permissions/profiles.js +66 -0
  19. package/src/pins.js +36 -0
  20. package/src/platform/index.js +76 -0
  21. package/src/platform/macos.js +129 -0
  22. package/src/platform/service.js +2 -0
  23. package/src/process.js +56 -0
  24. package/src/refs.js +146 -0
  25. package/src/secrets.js +51 -0
  26. package/src/server.js +146 -0
  27. package/src/session.js +140 -0
  28. package/src/text.js +68 -0
  29. package/src/tools/artifacts.js +288 -0
  30. package/src/tools/audit.js +53 -0
  31. package/src/tools/environments.js +147 -0
  32. package/src/tools/files.js +101 -0
  33. package/src/tools/index.js +33 -0
  34. package/src/tools/issues.js +465 -0
  35. package/src/tools/merge-requests.js +698 -0
  36. package/src/tools/packages.js +322 -0
  37. package/src/tools/pipelines.js +415 -0
  38. package/src/tools/registry.js +107 -0
  39. package/src/tools/repositories.js +174 -0
  40. package/src/tools/schedules.js +521 -0
  41. package/src/tools/shared.js +93 -0
  42. package/src/tools/variables.js +294 -0
  43. package/src/tools/wikis.js +168 -0
  44. package/src/zip.js +178 -0
@@ -0,0 +1,698 @@
1
+ import { z } from "zod";
2
+ import { localBranch } from "../git.js";
3
+ import { projectId } from "../gitlab/client.js";
4
+ import { computeDiff } from "../gitlab/diff.js";
5
+ import { formatRef } from "../refs.js";
6
+ import { PAGE_INPUT, UNTRUSTED, pick } from "./shared.js";
7
+
8
+ /** Characters of diffs returned by one call of mr_diff. */
9
+ const MAX_DIFF_CHARS = 50_000;
10
+
11
+ /** Pages of lists read at most where a tool needs all items, e.g. changed files. */
12
+ const MAX_PAGES = 30;
13
+
14
+ const MR_INPUT = z.union( [ z.number().int().min( 1 ), z.string().regex( /^!?\d{1,9}$/ ) ] )
15
+ .describe( "Number of the merge request in its project, e.g. 12 or \"!12\"" );
16
+
17
+ const USER_INPUT = z.string().min( 1 ).max( 255 ).regex( /^(?:[\w.]|-)+$/ );
18
+
19
+ const DRAFT_PREFIX = /^\s*(?:\[draft\]|\(draft\)|draft:|draft\s+-|wip:|\[wip\])\s*/i;
20
+
21
+ /**
22
+ * @param {number|string} value
23
+ * @returns {number}
24
+ */
25
+ function iidOf( value ) {
26
+ return Number( String( value ).replace( /^!/, "" ) );
27
+ }
28
+
29
+ /**
30
+ * @param {import("../refs.js").RepoRef} repo
31
+ * @param {number|string} mr
32
+ * @param {string} [suffix]
33
+ * @returns {string}
34
+ */
35
+ function mrEndpoint( repo, mr, suffix = "" ) {
36
+ return `projects/${projectId( repo )}/merge_requests/${iidOf( mr )}${suffix}`;
37
+ }
38
+
39
+ /**
40
+ * @param {string} title
41
+ * @returns {string}
42
+ */
43
+ function withoutDraft( title ) {
44
+ return title.replace( DRAFT_PREFIX, "" );
45
+ }
46
+
47
+ /**
48
+ * @param {any} user
49
+ * @returns {string|undefined}
50
+ */
51
+ const username = user => user?.username;
52
+
53
+ /**
54
+ * Basic properties of a merge request, as lists show them.
55
+ *
56
+ * @param {any} mr
57
+ * @returns {Record<string, unknown>}
58
+ */
59
+ function summary( mr ) {
60
+ return pick( mr, {
61
+ mr: "iid",
62
+ title: source => withoutDraft( source.title ?? "" ),
63
+ draft: source => source.draft || source.work_in_progress || undefined,
64
+ state: "state",
65
+ author: source => username( source.author ),
66
+ sourceBranch: "source_branch",
67
+ targetBranch: "target_branch",
68
+ updated: "updated_at",
69
+ webUrl: "web_url",
70
+ } );
71
+ }
72
+
73
+ /**
74
+ * All properties of a merge request an agent needs to work with it.
75
+ *
76
+ * @param {any} mr
77
+ * @returns {Record<string, unknown>}
78
+ */
79
+ function details( mr ) {
80
+ return {
81
+ ...summary( mr ),
82
+ ...pick( mr, {
83
+ description: "description",
84
+ assignees: source => source.assignees?.map( username ),
85
+ reviewers: source => source.reviewers?.map( username ),
86
+ labels: source => ( source.labels?.length ? source.labels : undefined ),
87
+ milestone: source => source.milestone?.title,
88
+ head: "sha",
89
+ mergeStatus: "detailed_merge_status",
90
+ conflicts: source => source.has_conflicts || undefined,
91
+ pipeline: source => ( source.head_pipeline ? { id: source.head_pipeline.id, status: source.head_pipeline.status } : undefined ),
92
+ autoMerge: source => source.merge_when_pipeline_succeeds || undefined,
93
+ squash: source => source.squash || undefined,
94
+ removeSourceBranch: source => source.force_remove_source_branch || undefined,
95
+ created: "created_at",
96
+ merged: "merged_at",
97
+ mergedBy: source => username( source.merged_by ?? source.merge_user ),
98
+ closed: "closed_at",
99
+ } ),
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Converts user names into the IDs GitLab takes, "me" being the user of the token.
105
+ *
106
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
107
+ * @param {import("../hosts.js").Host} host
108
+ * @param {string[]} names
109
+ * @returns {Promise<number[]>}
110
+ */
111
+ async function userIds( gitlab, host, names ) {
112
+ return Promise.all( names.map( async name => {
113
+ if ( name === "me" ) {
114
+ return ( await gitlab.currentUser( host ) ).id;
115
+ }
116
+
117
+ const [user] = await gitlab.get( host, "users", { username: name } );
118
+
119
+ if ( !user ) {
120
+ throw new Error( `there is no user "${name}" at ${host.name}` );
121
+ }
122
+
123
+ return user.id;
124
+ } ) );
125
+ }
126
+
127
+ /**
128
+ * Reads all pages of a list, up to a limit.
129
+ *
130
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
131
+ * @param {import("../hosts.js").Host} host
132
+ * @param {string} endpoint
133
+ * @returns {Promise<{ items: any[], complete: boolean }>}
134
+ */
135
+ async function readAll( gitlab, host, endpoint ) {
136
+ const items = [];
137
+
138
+ for ( let page = 1; page <= MAX_PAGES; page++ ) {
139
+ const result = await gitlab.list( host, endpoint, { page, perPage: 100 } ); // eslint-disable-line no-await-in-loop
140
+
141
+ items.push( ...result.items );
142
+
143
+ if ( !result.nextPage ) {
144
+ return { items, complete: true };
145
+ }
146
+ }
147
+
148
+ return { items, complete: false };
149
+ }
150
+
151
+ /**
152
+ * @param {any} file entry of GitLab's list of diffs
153
+ * @returns {"added"|"deleted"|"renamed"|"modified"}
154
+ */
155
+ function changeOf( file ) {
156
+ return file.new_file ? "added" : file.deleted_file ? "deleted" : file.renamed_file ? "renamed" : "modified";
157
+ }
158
+
159
+ /**
160
+ * Describes a merge request for a confirmation dialog.
161
+ *
162
+ * @param {import("./shared.js").ToolContext} context
163
+ * @param {number|string} mr
164
+ * @returns {Promise<string>}
165
+ */
166
+ async function describeForDialog( { gitlab, repo }, mr ) {
167
+ const data = await gitlab.get( repo.host, mrEndpoint( repo, mr ) );
168
+
169
+ return `!${data.iid} "${withoutDraft( data.title )}" by ${username( data.author )} in ${formatRef( repo )}, ${data.source_branch} → ${data.target_branch}` +
170
+ `${data.head_pipeline ? `, pipeline ${data.head_pipeline.status}` : ""}`;
171
+ }
172
+
173
+ /**
174
+ * Fetches a merge request and refuses merging what can't or shouldn't be
175
+ * merged, before the user is asked to confirm.
176
+ *
177
+ * @param {{ repo: import("../refs.js").RepoRef, gitlab: import("../gitlab/client.js").GitLabClient }} context
178
+ * @param {{ mr: number|string, when?: string, sha?: string }} args
179
+ * @returns {Promise<any>} the merge request
180
+ */
181
+ async function mergeable( { repo, gitlab }, { mr, when = "now", sha } ) {
182
+ const current = await gitlab.get( repo.host, mrEndpoint( repo, mr ) );
183
+
184
+ if ( current.state !== "opened" ) {
185
+ throw new Error( `!${current.iid} is ${current.state}` );
186
+ }
187
+
188
+ if ( current.draft || current.work_in_progress ) {
189
+ throw new Error( `!${current.iid} is a draft, mark it ready first` );
190
+ }
191
+
192
+ if ( current.has_conflicts ) {
193
+ throw new Error( `!${current.iid} has conflicts with ${current.target_branch}` );
194
+ }
195
+
196
+ if ( sha && current.sha !== sha ) {
197
+ throw new Error( `the head of !${current.iid} is ${current.sha} now, not ${sha}: review the new commits first` );
198
+ }
199
+
200
+ if ( when === "now" && current.detailed_merge_status && ![ "mergeable", "checking", "unchecked" ].includes( current.detailed_merge_status ) ) {
201
+ throw new Error( `GitLab doesn't allow merging !${current.iid} now: ${current.detailed_merge_status.replace( /_/g, " " )}` );
202
+ }
203
+
204
+ return current;
205
+ }
206
+
207
+ /** @type {import("./shared.js").ToolDefinition[]} */
208
+ export const mergeRequestTools = [
209
+ {
210
+ name: "mr_list",
211
+ title: "List merge requests",
212
+ description: "Lists merge requests of a repository, most recently updated first: open ones by default, optionally by author, assignee or reviewer (\"me\" for the user), branches, draft state or text.",
213
+ permission: "mr.read",
214
+ usesRepo: true,
215
+ input: {
216
+ state: z.enum( [ "opened", "merged", "closed", "all" ] ).optional().describe( "Default: opened" ),
217
+ author: USER_INPUT.optional().describe( "User name of the author, \"me\" for the user" ),
218
+ assignee: USER_INPUT.optional().describe( "User name of an assignee, \"me\" for the user" ),
219
+ reviewer: USER_INPUT.optional().describe( "User name of a reviewer, \"me\" for the user" ),
220
+ sourceBranch: z.string().min( 1 ).max( 250 ).optional(),
221
+ targetBranch: z.string().min( 1 ).max( 250 ).optional(),
222
+ draft: z.boolean().optional().describe( "true for drafts only, false for ready ones only" ),
223
+ search: z.string().min( 2 ).max( 100 ).optional().describe( "Text in title or description" ),
224
+ page: PAGE_INPUT,
225
+ },
226
+ async handler( { state = "opened", author, assignee, reviewer, sourceBranch, targetBranch, draft, search, page = 1 }, { repo, gitlab } ) {
227
+ const name = async value => ( value === "me" ? ( await gitlab.currentUser( repo.host ) ).username : value );
228
+ const { items, nextPage } = await gitlab.list( repo.host, `projects/${projectId( repo )}/merge_requests`, {
229
+ query: {
230
+ state,
231
+ author_username: author && await name( author ),
232
+ assignee_username: assignee && await name( assignee ),
233
+ reviewer_username: reviewer && await name( reviewer ),
234
+ source_branch: sourceBranch,
235
+ target_branch: targetBranch,
236
+ wip: draft === undefined ? undefined : draft ? "yes" : "no",
237
+ search,
238
+ order_by: "updated_at",
239
+ },
240
+ page,
241
+ perPage: 30,
242
+ } );
243
+
244
+ return { repo: formatRef( repo ), mergeRequests: items.map( summary ), ...nextPage ? { nextPage } : {} };
245
+ },
246
+ },
247
+ {
248
+ name: "mr_get",
249
+ title: "Read a merge request",
250
+ description: `Returns a merge request with description, branches, head commit, pipeline, merge status, approvals, assignees and reviewers. ${UNTRUSTED}`,
251
+ permission: "mr.read",
252
+ usesRepo: true,
253
+ input: { mr: MR_INPUT },
254
+ async handler( { mr }, { repo, gitlab } ) {
255
+ const [ data, approvals ] = await Promise.all( [
256
+ gitlab.get( repo.host, mrEndpoint( repo, mr ) ),
257
+ gitlab.get( repo.host, mrEndpoint( repo, mr, "/approvals" ) ).catch( () => null ),
258
+ ] );
259
+
260
+ return {
261
+ repo: formatRef( repo ),
262
+ ...details( data ),
263
+ ...approvals ? { approvedBy: approvals.approved_by?.map( entry => username( entry.user ) ) ?? [] } : {},
264
+ ...approvals?.approvals_left ? { approvalsLeft: approvals.approvals_left } : {},
265
+ };
266
+ },
267
+ },
268
+ {
269
+ name: "mr_changes",
270
+ title: "List files changed by a merge request",
271
+ description: "Lists the files a merge request changes: added, modified, deleted or renamed, compared with the merge base of source and target branch.",
272
+ permission: "mr.read",
273
+ usesRepo: true,
274
+ input: { mr: MR_INPUT },
275
+ async handler( { mr }, { repo, gitlab } ) {
276
+ const { items, complete } = await readAll( gitlab, repo.host, mrEndpoint( repo, mr, "/diffs" ) );
277
+
278
+ return {
279
+ repo: formatRef( repo ),
280
+ mr: iidOf( mr ),
281
+ files: items.map( file => ( {
282
+ path: file.new_path,
283
+ ...file.renamed_file ? { oldPath: file.old_path } : {},
284
+ change: changeOf( file ),
285
+ } ) ),
286
+ ...complete ? {} : { note: `only the first ${items.length} files are listed` },
287
+ };
288
+ },
289
+ },
290
+ {
291
+ name: "mr_diff",
292
+ title: "Show the changes of a merge request",
293
+ description: `Returns the changes of a merge request as unified diffs, of all files page by page or of selected ones, with as many lines of context as asked for. Line numbers in hunk headers are those mr_comment takes. ${UNTRUSTED}`,
294
+ permission: "mr.read",
295
+ usesRepo: true,
296
+ input: {
297
+ mr: MR_INPUT,
298
+ files: z.array( z.string().min( 1 ).max( 1000 ) ).max( 100 ).optional().describe( "Paths of the files to show, default: all" ),
299
+ context: z.number().int().min( 0 ).max( 100 ).optional().describe( "Lines of context around changes, default: 3" ),
300
+ offset: z.number().int().min( 0 ).optional().describe( "Number of files to skip, as \"nextOffset\" of the previous call tells" ),
301
+ },
302
+ async handler( { mr, files: selection, context = 3, offset = 0 }, { repo, gitlab } ) {
303
+ const [ data, { items } ] = await Promise.all( [
304
+ gitlab.get( repo.host, mrEndpoint( repo, mr ) ),
305
+ readAll( gitlab, repo.host, mrEndpoint( repo, mr, "/diffs" ) ),
306
+ ] );
307
+
308
+ const wanted = selection ? items.filter( file => selection.includes( file.new_path ) || selection.includes( file.old_path ) ) : items;
309
+ const versions = { base: data.diff_refs?.base_sha, head: data.diff_refs?.head_sha ?? data.sha };
310
+ const files = [];
311
+ let chars = 0;
312
+ let index = offset;
313
+
314
+ for ( ; index < wanted.length; index++ ) {
315
+ const file = wanted[index];
316
+ const entry = { path: file.new_path, ...file.renamed_file ? { oldPath: file.old_path } : {}, change: changeOf( file ) };
317
+ let result;
318
+
319
+ if ( context === 3 && file.diff && !file.too_large && !file.collapsed ) {
320
+ result = { diff: file.diff };
321
+ } else if ( versions.base && versions.head ) {
322
+ // eslint-disable-next-line no-await-in-loop
323
+ result = await computeDiff( gitlab, repo, { oldPath: file.old_path, newPath: file.new_path, added: file.new_file, deleted: file.deleted_file }, versions, context );
324
+ } else {
325
+ result = { omitted: "GitLab provides no diff for this file" };
326
+ }
327
+
328
+ if ( result.diff !== undefined ) {
329
+ if ( chars + result.diff.length > MAX_DIFF_CHARS ) {
330
+ if ( files.length > 0 ) {
331
+ break;
332
+ }
333
+
334
+ result = { diff: result.diff.slice( 0, MAX_DIFF_CHARS ), cut: true };
335
+ }
336
+
337
+ chars += result.diff.length;
338
+ }
339
+
340
+ files.push( { ...entry, ...result } );
341
+ }
342
+
343
+ return {
344
+ repo: formatRef( repo ),
345
+ mr: iidOf( mr ),
346
+ base: versions.base,
347
+ head: versions.head,
348
+ files,
349
+ ...index < wanted.length ? { nextOffset: index } : {},
350
+ ...selection && wanted.length < selection.length ? { note: "some of the files asked for aren't changed by the merge request" } : {},
351
+ };
352
+ },
353
+ },
354
+ {
355
+ name: "mr_create",
356
+ title: "Create a merge request",
357
+ description: "Creates a merge request from a branch that has been pushed, as draft unless told otherwise, assigned to the user. Without \"sourceBranch\" it takes the branch checked out in the local clone and warns about commits that aren't pushed; without \"targetBranch\" the default branch. Use \"Closes #12\" in the description to close issues when merged.",
358
+ permission: "mr.create",
359
+ usesRepo: true,
360
+ mutates: true,
361
+ input: {
362
+ title: z.string().min( 1 ).max( 255 ),
363
+ description: z.string().max( 100_000 ).optional().describe( "Markdown" ),
364
+ sourceBranch: z.string().min( 1 ).max( 250 ).optional(),
365
+ targetBranch: z.string().min( 1 ).max( 250 ).optional(),
366
+ draft: z.boolean().optional().describe( "Default: true" ),
367
+ reviewers: z.array( USER_INPUT ).max( 20 ).optional().describe( "User names of reviewers" ),
368
+ assignToMe: z.boolean().optional().describe( "Default: true" ),
369
+ labels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
370
+ removeSourceBranch: z.boolean().optional().describe( "Delete the source branch when merged, default: true" ),
371
+ squash: z.boolean().optional().describe( "Squash commits when merged" ),
372
+ },
373
+ async handler( args, { repo, gitlab, cwd } ) {
374
+ const { title, description, reviewers, labels, squash, draft = true, assignToMe = true, removeSourceBranch = true } = args;
375
+ const warnings = [];
376
+ let source = args.sourceBranch;
377
+
378
+ if ( !source ) {
379
+ if ( args.repo ) {
380
+ throw new Error( "name the \"sourceBranch\", it can only be taken from a local clone if \"repo\" isn't given" );
381
+ }
382
+
383
+ const local = await localBranch( args.directory ?? cwd );
384
+
385
+ source = local.branch;
386
+
387
+ if ( local.unpushed === null ) {
388
+ warnings.push( `branch ${source} has no upstream, the merge request shows what has been pushed to ${source} only` );
389
+ } else if ( local.unpushed > 0 ) {
390
+ warnings.push( `${local.unpushed} commit(s) of ${source} haven't been pushed yet and aren't part of the merge request` );
391
+ }
392
+ }
393
+
394
+ try {
395
+ await gitlab.get( repo.host, `projects/${projectId( repo )}/repository/branches/${encodeURIComponent( source )}` );
396
+ } catch ( error ) {
397
+ if ( error.status === 404 ) {
398
+ throw new Error( `branch ${source} doesn't exist at ${repo.host.name}, it has to be pushed first` );
399
+ }
400
+
401
+ throw error;
402
+ }
403
+
404
+ const target = args.targetBranch ?? ( await gitlab.get( repo.host, `projects/${projectId( repo )}` ) ).default_branch;
405
+
406
+ if ( source === target ) {
407
+ throw new Error( `source and target branch are both ${source}` );
408
+ }
409
+
410
+ const created = await gitlab.post( repo.host, `projects/${projectId( repo )}/merge_requests`, {
411
+ source_branch: source,
412
+ target_branch: target,
413
+ title: draft ? `Draft: ${withoutDraft( title )}` : withoutDraft( title ),
414
+ description,
415
+ assignee_ids: assignToMe ? await userIds( gitlab, repo.host, ["me"] ) : undefined,
416
+ reviewer_ids: reviewers?.length ? await userIds( gitlab, repo.host, reviewers ) : undefined,
417
+ labels: labels?.join( "," ),
418
+ remove_source_branch: removeSourceBranch,
419
+ squash,
420
+ } );
421
+
422
+ return { repo: formatRef( repo ), ...details( created ), ...warnings.length ? { warnings } : {} };
423
+ },
424
+ },
425
+ {
426
+ name: "mr_update",
427
+ title: "Change a merge request",
428
+ description: "Changes title, description, draft state, target branch, labels, assignees or reviewers of a merge request. Assignees and reviewers given replace the current ones.",
429
+ permission: "mr.update",
430
+ usesRepo: true,
431
+ mutates: true,
432
+ input: {
433
+ mr: MR_INPUT,
434
+ title: z.string().min( 1 ).max( 255 ).optional(),
435
+ description: z.string().max( 100_000 ).optional().describe( "Markdown, replaces the description" ),
436
+ draft: z.boolean().optional().describe( "true turns it into a draft, false marks it ready" ),
437
+ targetBranch: z.string().min( 1 ).max( 250 ).optional(),
438
+ addLabels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
439
+ removeLabels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
440
+ assignees: z.array( USER_INPUT ).max( 20 ).optional().describe( "User names, \"me\" for the user, empty to remove all" ),
441
+ reviewers: z.array( USER_INPUT ).max( 20 ).optional().describe( "User names, \"me\" for the user, empty to remove all" ),
442
+ },
443
+ async handler( { mr, title, description, draft, targetBranch, addLabels, removeLabels, assignees, reviewers }, { repo, gitlab } ) {
444
+ const body = {
445
+ description,
446
+ target_branch: targetBranch,
447
+ add_labels: addLabels?.join( "," ),
448
+ remove_labels: removeLabels?.join( "," ),
449
+ assignee_ids: assignees && await userIds( gitlab, repo.host, assignees ),
450
+ reviewer_ids: reviewers && await userIds( gitlab, repo.host, reviewers ),
451
+ };
452
+
453
+ if ( title !== undefined || draft !== undefined ) {
454
+ const current = await gitlab.get( repo.host, mrEndpoint( repo, mr ) );
455
+ const isDraft = draft ?? Boolean( current.draft || current.work_in_progress );
456
+ const plain = withoutDraft( title ?? current.title );
457
+
458
+ body.title = isDraft ? `Draft: ${plain}` : plain;
459
+ }
460
+
461
+ if ( Object.values( body ).every( value => value === undefined ) ) {
462
+ throw new Error( "nothing to change" );
463
+ }
464
+
465
+ // GitLab ignores empty lists, 0 removes everybody
466
+ if ( body.assignee_ids?.length === 0 ) {
467
+ body.assignee_ids = [0];
468
+ }
469
+
470
+ if ( body.reviewer_ids?.length === 0 ) {
471
+ body.reviewer_ids = [0];
472
+ }
473
+
474
+ return { repo: formatRef( repo ), ...details( await gitlab.put( repo.host, mrEndpoint( repo, mr ), body ) ) };
475
+ },
476
+ },
477
+ {
478
+ name: "mr_close",
479
+ title: "Close or reopen a merge request",
480
+ description: "Closes an open merge request without merging it, or reopens a closed one.",
481
+ permission: "mr.close",
482
+ usesRepo: true,
483
+ mutates: true,
484
+ input: {
485
+ mr: MR_INPUT,
486
+ reopen: z.boolean().optional().describe( "true to reopen a closed merge request" ),
487
+ },
488
+ confirmMessage: async( { mr, reopen }, context ) => `An agent wants to ${reopen ? "reopen" : "close"} the merge request ${await describeForDialog( context, mr )}.`,
489
+ async handler( { mr, reopen = false }, { repo, gitlab } ) {
490
+ return { repo: formatRef( repo ), ...details( await gitlab.put( repo.host, mrEndpoint( repo, mr ), { state_event: reopen ? "reopen" : "close" } ) ) };
491
+ },
492
+ },
493
+ {
494
+ name: "mr_comment_list",
495
+ title: "List comments of a merge request",
496
+ description: `Lists the comment threads of a merge request with file and line, by default the unresolved ones. Comments of the user are marked "mine". ${UNTRUSTED}`,
497
+ permission: "mr.read",
498
+ usesRepo: true,
499
+ input: {
500
+ mr: MR_INPUT,
501
+ status: z.enum( [ "unresolved", "resolved", "all" ] ).optional().describe( "Default: unresolved threads; \"all\" includes plain comments" ),
502
+ },
503
+ async handler( { mr, status = "unresolved" }, { repo, gitlab } ) {
504
+ const [ { items, complete }, me ] = await Promise.all( [
505
+ readAll( gitlab, repo.host, mrEndpoint( repo, mr, "/discussions" ) ),
506
+ gitlab.currentUser( repo.host ),
507
+ ] );
508
+
509
+ const threads = items
510
+ .map( discussion => ( { ...discussion, notes: ( discussion.notes ?? [] ).filter( note => !note.system ) } ) )
511
+ .filter( discussion => discussion.notes.length > 0 )
512
+ .filter( discussion => {
513
+ const first = discussion.notes[0];
514
+
515
+ switch ( status ) {
516
+ case "unresolved" :
517
+ return first.resolvable && !first.resolved;
518
+ case "resolved" :
519
+ return first.resolvable && first.resolved;
520
+ default :
521
+ return true;
522
+ }
523
+ } )
524
+ .map( discussion => {
525
+ const first = discussion.notes[0];
526
+ const position = first.position;
527
+
528
+ return {
529
+ thread: discussion.id,
530
+ ...first.resolvable ? { resolved: Boolean( first.resolved ) } : {},
531
+ ...position ? pick( position, { file: source => source.new_path ?? source.old_path, line: "new_line", oldLine: "old_line" } ) : {},
532
+ notes: discussion.notes.map( note => ( {
533
+ author: username( note.author ),
534
+ ...note.author?.id === me.id ? { mine: true } : {},
535
+ created: note.created_at,
536
+ body: note.body,
537
+ } ) ),
538
+ };
539
+ } );
540
+
541
+ return { repo: formatRef( repo ), mr: iidOf( mr ), threads, ...complete ? {} : { note: "not all threads could be read" } };
542
+ },
543
+ },
544
+ {
545
+ name: "mr_comment",
546
+ title: "Comment on a merge request",
547
+ description: "Starts a thread on a merge request, optionally on a line of a changed file, replies in a thread, or resolves or reopens a thread. For a line, give \"line\" as numbered in the new version (hunk headers of mr_diff), or \"oldLine\" for a removed line.",
548
+ permission: "mr.comment",
549
+ usesRepo: true,
550
+ mutates: true,
551
+ input: {
552
+ mr: MR_INPUT,
553
+ body: z.string().min( 1 ).max( 100_000 ).optional().describe( "Markdown" ),
554
+ thread: z.string().regex( /^[0-9a-f]{8,64}$/ ).optional().describe( "Thread to reply in or resolve, as mr_comment_list returns it" ),
555
+ resolve: z.boolean().optional().describe( "true resolves the thread, false reopens it" ),
556
+ file: z.string().min( 1 ).max( 1000 ).optional().describe( "Path of a changed file to comment on" ),
557
+ line: z.number().int().min( 1 ).optional(),
558
+ oldLine: z.number().int().min( 1 ).optional(),
559
+ },
560
+ async handler( { mr, body, thread, resolve, file, line, oldLine }, { repo, gitlab } ) {
561
+ const result = { repo: formatRef( repo ), mr: iidOf( mr ) };
562
+
563
+ if ( thread ) {
564
+ if ( file || line || oldLine ) {
565
+ throw new Error( "a reply belongs to the thread, \"file\" and lines can't be given" );
566
+ }
567
+
568
+ if ( !body && resolve === undefined ) {
569
+ throw new Error( "give \"body\" to reply or \"resolve\"" );
570
+ }
571
+
572
+ if ( body ) {
573
+ const note = await gitlab.post( repo.host, mrEndpoint( repo, mr, `/discussions/${thread}/notes` ), { body } );
574
+
575
+ result.note = note.id;
576
+ }
577
+
578
+ if ( resolve !== undefined ) {
579
+ await gitlab.put( repo.host, mrEndpoint( repo, mr, `/discussions/${thread}` ), { resolved: resolve } );
580
+ result.resolved = resolve;
581
+ }
582
+
583
+ return { ...result, thread };
584
+ }
585
+
586
+ if ( !body ) {
587
+ throw new Error( "give \"body\" for a new thread" );
588
+ }
589
+
590
+ if ( resolve !== undefined ) {
591
+ throw new Error( "\"resolve\" needs a \"thread\"" );
592
+ }
593
+
594
+ let position;
595
+
596
+ if ( file ) {
597
+ if ( !line && !oldLine ) {
598
+ throw new Error( "a comment on a file needs \"line\" or \"oldLine\"" );
599
+ }
600
+
601
+ const data = await gitlab.get( repo.host, mrEndpoint( repo, mr ) );
602
+ const { items } = await readAll( gitlab, repo.host, mrEndpoint( repo, mr, "/diffs" ) );
603
+ const changed = items.find( entry => entry.new_path === file || entry.old_path === file );
604
+
605
+ if ( !changed ) {
606
+ throw new Error( `${file} isn't changed by the merge request` );
607
+ }
608
+
609
+ position = {
610
+ position_type: "text",
611
+ base_sha: data.diff_refs.base_sha,
612
+ start_sha: data.diff_refs.start_sha,
613
+ head_sha: data.diff_refs.head_sha,
614
+ old_path: changed.old_path,
615
+ new_path: changed.new_path,
616
+ ...line ? { new_line: line } : {},
617
+ ...oldLine ? { old_line: oldLine } : {},
618
+ };
619
+ } else if ( line || oldLine ) {
620
+ throw new Error( "lines need a \"file\"" );
621
+ }
622
+
623
+ const discussion = await gitlab.post( repo.host, mrEndpoint( repo, mr, "/discussions" ), { body, position } );
624
+
625
+ return { ...result, thread: discussion.id, ...file ? { file, ...line ? { line } : {}, ...oldLine ? { oldLine } : {} } : {} };
626
+ },
627
+ },
628
+ {
629
+ name: "mr_vote",
630
+ title: "Approve a merge request",
631
+ description: "Approves a merge request as the user, or revokes the user's approval. Pass the head commit from mr_get as \"sha\" so commits pushed meanwhile aren't approved unseen.",
632
+ permission: "mr.vote",
633
+ usesRepo: true,
634
+ mutates: true,
635
+ input: {
636
+ mr: MR_INPUT,
637
+ approve: z.boolean().optional().describe( "false revokes the approval, default: true" ),
638
+ sha: z.string().regex( /^[0-9a-f]{40,64}$/ ).optional().describe( "Head commit the approval is for" ),
639
+ },
640
+ confirmMessage: async( { mr, approve = true }, context ) => `An agent wants to ${approve ? "approve" : "revoke your approval of"} the merge request ${await describeForDialog( context, mr )}.`,
641
+ async handler( { mr, approve = true, sha }, { repo, gitlab } ) {
642
+ const approvals = approve ?
643
+ await gitlab.post( repo.host, mrEndpoint( repo, mr, "/approve" ), sha ? { sha } : undefined ) :
644
+ await gitlab.post( repo.host, mrEndpoint( repo, mr, "/unapprove" ) );
645
+
646
+ return {
647
+ repo: formatRef( repo ),
648
+ mr: iidOf( mr ),
649
+ approved: approve,
650
+ approvedBy: approvals?.approved_by?.map( entry => username( entry.user ) ),
651
+ };
652
+ },
653
+ },
654
+ {
655
+ name: "mr_merge",
656
+ title: "Merge a merge request",
657
+ description: "Merges a merge request now, or has GitLab merge it once its pipeline succeeds, or cancels that. Never bypasses the rules of the project: GitLab refuses what they don't allow. Drafts, closed merge requests and those with conflicts are refused. Pass the head commit from mr_get as \"sha\" so commits pushed meanwhile aren't merged unseen.",
658
+ permission: "mr.merge",
659
+ usesRepo: true,
660
+ mutates: true,
661
+ destructive: true,
662
+ input: {
663
+ mr: MR_INPUT,
664
+ when: z.enum( [ "now", "pipelineSucceeds", "cancel" ] ).optional().describe( "Default: now" ),
665
+ sha: z.string().regex( /^[0-9a-f]{40,64}$/ ).optional().describe( "Head commit expected, GitLab refuses if the branch has changed" ),
666
+ squash: z.boolean().optional(),
667
+ removeSourceBranch: z.boolean().optional(),
668
+ message: z.string().min( 1 ).max( 10_000 ).optional().describe( "Merge commit message, or squash commit message when squashing" ),
669
+ },
670
+ confirmMessage: async( { mr, when = "now" }, context ) => {
671
+ const action = { now: "merge", pipelineSucceeds: "merge when its pipeline succeeds", cancel: "cancel the automatic merge of" }[when];
672
+
673
+ return `An agent wants to ${action} the merge request ${await describeForDialog( context, mr )}.`;
674
+ },
675
+ precheck: async( args, context ) => {
676
+ if ( args.when !== "cancel" ) {
677
+ await mergeable( context, args );
678
+ }
679
+ },
680
+ async handler( { mr, when = "now", sha, squash, removeSourceBranch, message }, { repo, gitlab } ) {
681
+ if ( when === "cancel" ) {
682
+ return { repo: formatRef( repo ), ...details( await gitlab.post( repo.host, mrEndpoint( repo, mr, "/cancel_merge_when_pipeline_succeeds" ) ) ) };
683
+ }
684
+
685
+ const current = await mergeable( { repo, gitlab }, { mr, when, sha } );
686
+
687
+ const merged = await gitlab.put( repo.host, mrEndpoint( repo, mr, "/merge" ), {
688
+ sha: sha ?? current.sha,
689
+ squash,
690
+ should_remove_source_branch: removeSourceBranch,
691
+ ...message ? { [squash ? "squash_commit_message" : "merge_commit_message"]: message } : {},
692
+ ...when === "pipelineSucceeds" ? { merge_when_pipeline_succeeds: true, auto_merge: true } : {},
693
+ } );
694
+
695
+ return { repo: formatRef( repo ), ...details( merged ) };
696
+ },
697
+ },
698
+ ];