@leitwerk-dev/gitlab 0.0.0-bootstrap.0 → 0.2.1

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.
package/src/tools.ts ADDED
@@ -0,0 +1,208 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ExternalWrites } from "@leitwerk-dev/external-writes";
3
+
4
+ import {
5
+ type IntegrationToolExecutionContext,
6
+ numberArg,
7
+ projectParameters,
8
+ type ServerExtensionAPI,
9
+ stringArg,
10
+ } from "@leitwerk-dev/process-sdk";
11
+ import type { GitLabIntegration } from "./capability.js";
12
+ import { type GitLabClientLike, GitLabError, observeMergeRequest } from "./client.js";
13
+
14
+ async function existingRemote<T>(read: () => Promise<T>): Promise<T | null> {
15
+ try {
16
+ return await read();
17
+ } catch (error) {
18
+ if (error instanceof GitLabError && error.status === 404) return null;
19
+ throw error;
20
+ }
21
+ }
22
+ /** @public */
23
+ export function resolveGitLabBinding(
24
+ ctx: Pick<IntegrationToolExecutionContext, "project" | "process">,
25
+ ): {
26
+ /** @public */
27
+ profile: string;
28
+ /** @public */
29
+ projectId: number;
30
+ /** @public */
31
+ iid: number;
32
+ } {
33
+ if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
34
+ throw new Error("An authorized GitLab process project is required");
35
+ const binding = ctx.project.metadata?.gitlab as
36
+ | { profile?: unknown; projectId?: unknown; iid?: unknown }
37
+ | undefined;
38
+ if (
39
+ !binding ||
40
+ typeof binding.profile !== "string" ||
41
+ typeof binding.projectId !== "number" ||
42
+ typeof binding.iid !== "number"
43
+ )
44
+ throw new Error("Invalid GitLab project binding");
45
+ return { profile: binding.profile, projectId: binding.projectId, iid: binding.iid };
46
+ }
47
+ /** @internal */
48
+ export async function ensureGitLabComment(input: {
49
+ /** @internal */
50
+ client: GitLabClientLike;
51
+ /** @internal */
52
+ writes: ExternalWrites;
53
+ /** @internal */
54
+ instanceId: string;
55
+ /** @internal */
56
+ projectId: number;
57
+ /** @internal */
58
+ iid: number;
59
+ /** @internal */
60
+ writeKey: string;
61
+ /** @internal */
62
+ body: string;
63
+ /** @internal */
64
+ discussionId?: string;
65
+ /** @internal */
66
+ signal?: AbortSignal;
67
+ }): Promise<{
68
+ /** @internal */
69
+ marker: string;
70
+ }> {
71
+ const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
72
+ const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
73
+ if (input.discussionId) identity.push(input.discussionId);
74
+ const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
75
+ const marker = `<!-- leitwerk:gitlab:${digest} -->`;
76
+ const find = async () => {
77
+ const notes = input.discussionId
78
+ ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes
79
+ : await client.listNotes(projectId, iid, signal);
80
+ return notes.find((note) => note.body.includes(marker));
81
+ };
82
+ await writes.ensure(
83
+ { writeType: "gitlab.comment", dedupKey: digest },
84
+ {
85
+ reconcile: () => existingRemote(async () => (await find()) ?? null),
86
+ execute: () => {
87
+ const body = `${input.body}\n\n${marker}`;
88
+ return input.discussionId
89
+ ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal)
90
+ : client.addNote(projectId, iid, body, signal);
91
+ },
92
+ toMetadata: (note) => ({ projectId, iid, noteId: note.id, marker }),
93
+ },
94
+ );
95
+ return { marker };
96
+ }
97
+ /** @public */
98
+ export async function ensureGitLabSeenReaction(input: {
99
+ /** @public */
100
+ client: GitLabClientLike;
101
+ /** @public */
102
+ writes: ExternalWrites;
103
+ /** @public */
104
+ instanceId: string;
105
+ /** @public */
106
+ projectId: number;
107
+ /** @public */
108
+ iid: number;
109
+ /** @public */
110
+ noteId: number;
111
+ /** @public */
112
+ signal?: AbortSignal;
113
+ }): Promise<void> {
114
+ const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
115
+ const digest = createHash("sha256")
116
+ .update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId]))
117
+ .digest("hex");
118
+ await writes.ensure(
119
+ { writeType: "gitlab.reaction", dedupKey: digest },
120
+ {
121
+ reconcile: () =>
122
+ existingRemote(async () => {
123
+ const identity = await client.resolveGitIdentity(signal);
124
+ return (
125
+ (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
126
+ (reaction) =>
127
+ reaction.name === "eyes" && reaction.user.username === identity.username,
128
+ ) ?? null
129
+ );
130
+ }),
131
+ execute: () => client.addNoteReaction(projectId, iid, noteId, "eyes", signal),
132
+ toMetadata: (reaction) => ({ projectId, iid, noteId, reactionId: reaction.id, name: "eyes" }),
133
+ },
134
+ );
135
+ }
136
+ /** @internal */
137
+ export function registerGitLabTools(api: ServerExtensionAPI, integration: GitLabIntegration) {
138
+ for (const [name, description, required] of [
139
+ ["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
140
+ ["gitlab_get_changes", "Read the MR changes", []],
141
+ ["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
142
+ ["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
143
+ [
144
+ "gitlab_get_job_trace",
145
+ "Read a bounded trace from a failed MR pipeline job",
146
+ ["pipelineId", "jobId"],
147
+ ],
148
+ ["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
149
+ [
150
+ "gitlab_reply",
151
+ "Post a retry-safe reply in an MR discussion",
152
+ ["body", "writeKey", "discussionId"],
153
+ ],
154
+ ] as const) {
155
+ api.tool<Record<string, unknown>>({
156
+ name,
157
+ description,
158
+ parameters: projectParameters(
159
+ {
160
+ pipelineId: { type: "integer" },
161
+ jobId: { type: "integer" },
162
+ maxBytes: { type: "integer" },
163
+ body: { type: "string" },
164
+ writeKey: { type: "string" },
165
+ discussionId: { type: "string" },
166
+ },
167
+ [...required],
168
+ ),
169
+ async execute(ctx, args) {
170
+ const b = resolveGitLabBinding(ctx);
171
+ const client = integration.client(b.profile);
172
+ if (name === "gitlab_observe_merge_request")
173
+ return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
174
+ if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
175
+ if (name === "gitlab_get_identity") return client.resolveGitIdentity(ctx.signal);
176
+ if (name === "gitlab_comment" || name === "gitlab_reply")
177
+ return ensureGitLabComment({
178
+ client,
179
+ writes: ctx.externalWrites,
180
+ instanceId: ctx.process.id,
181
+ projectId: b.projectId,
182
+ iid: b.iid,
183
+ writeKey: stringArg(args, "writeKey"),
184
+ body: stringArg(args, "body"),
185
+ ...(name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {}),
186
+ signal: ctx.signal,
187
+ });
188
+ const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
189
+ if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
190
+ throw new Error("Pipeline is not current for the authorized MR");
191
+ const jobs = await client.listFailedJobs(
192
+ observation.pipeline.project_id,
193
+ observation.pipeline.id,
194
+ ctx.signal,
195
+ );
196
+ if (name === "gitlab_list_failed_jobs") return jobs;
197
+ const job = jobs.find((job) => job.id === numberArg(args, "jobId"));
198
+ if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
199
+ return client.getJobTrace(
200
+ observation.pipeline.project_id,
201
+ job.id,
202
+ typeof args.maxBytes === "number" ? args.maxBytes : undefined,
203
+ ctx.signal,
204
+ );
205
+ },
206
+ });
207
+ }
208
+ }