Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

handlers.ts

500 lines18.0 KB

1import {
2 threadPullRequestsOf,
3 threadPullRequestKeysEqual,
4} from "@t3tools/shared/threadPullRequests";
5import {
6 CommandId,
7 pullRequestHostOf,
8 type OrchestrationProjectShell,
9 type OrchestrationV2ThreadShell,
10 type SourceControlProviderKind,
11 type ThreadId,
12 type ThreadPullRequestLink,
13} from "@t3tools/contracts";
14import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
15import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
16import {
17 normalizeThreadPullRequestKey,
18 resolveThreadPullRequestChains,
19 threadPullRequestKeyOf,
20 visibleThreadPullRequests,
21} from "@t3tools/shared/threadPullRequests";
22import * as Cause from "effect/Cause";
23import * as Crypto from "effect/Crypto";
24import * as Effect from "effect/Effect";
25import * as Option from "effect/Option";
26​
27import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
28import * as ProjectService from "../../../project/ProjectService.ts";
29import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
30import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
31import * as McpInvocationContext from "../../McpInvocationContext.ts";
32import * as McpToolAccess from "../../McpToolAccess.ts";
33import {
34 type ListThreadPullRequestsResult,
35 PullRequestLinkFailedError,
36 PullRequestUrlInvalidError,
37 PullRequestTargetIncompleteError,
38 PullRequestHostRequiredError,
39 PullRequestUnlinkFailedError,
40 PullRequestListFailedError,
41 PullRequestNotOpenError,
42 type PullRequestTargetInput,
43 PullRequestWatchFailedError,
44 PullRequestWatchFromSubagentError,
45 PullRequestThreadNotFoundError,
46 PullRequestThreadRequiredError,
47 PullRequestGuideFailedError,
48 PullRequestProjectNotFoundError,
49 PullRequestsToolkit,
50 type ThreadPullRequestEntry,
51} from "./tools.ts";
52​
53interface ResolvedTarget {
54 readonly host: string;
55 readonly repository: string;
56 readonly number: number;
57 readonly url: string;
59​
60function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
61 readonly host: string | null;
62 readonly kind: SourceControlProviderKind | null;
63} {
64 const identity = project?.repositoryIdentity;
65 const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;
66 if (!identity || kind === null) return { host: null, kind: null };
67 return {
68 host: pullRequestHostOf(identity, kind),
69 kind,
70 };
72​
73const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
74 input: PullRequestTargetInput,
75 project: OrchestrationProjectShell | undefined,
76) {
77 if (input.url !== undefined) {
78 const parsed = parseChangeRequestUrl(input.url);
79 if (parsed === null) {
80 return yield* new PullRequestUrlInvalidError({});
81 }
82 return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
83 }
84 if (input.repository === undefined || input.number === undefined) {
85 return yield* new PullRequestTargetIncompleteError({});
86 }
87 const projectHost = projectHostAndProvider(project);
88 const host = (input.host ?? projectHost.host)?.toLowerCase();
89 if (host === undefined) {
90 return yield* new PullRequestHostRequiredError({});
91 }
92 const repository = input.repository.toLowerCase();
93 const url =
94 changeRequestUrlFor(
95 host === projectHost.host ? projectHost.kind : null,
96 host,
97 repository,
98 input.number,
99 project?.repositoryIdentity?.locator.remoteUrl,
100 ) ?? `https://${host}/${repository}/pull/${input.number}`;
101 return {
102 ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
103 url,
104 } satisfies ResolvedTarget;
105});
106​
107function entryOf(
108 link: ThreadPullRequestLink,
109 chains: ReturnType<typeof resolveThreadPullRequestChains>,
110): ThreadPullRequestEntry {
111 const key = threadPullRequestKeyOf(link);
112 let stack: ThreadPullRequestEntry["stack"] = null;
113 for (const chain of chains) {
114 if (chain.layers.length < 2) continue;
115 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
116 if (index !== -1) {
117 stack = { kind: chain.kind, position: chain.depths[index]! + 1, size: chain.layers.length };
118 break;
119 }
120 }
121 return {
122 host: normalizeThreadPullRequestKey(link).host,
123 repository: link.repository,
124 number: link.number,
125 url: link.url,
126 source: link.source,
127 watching: link.watch !== undefined,
128 state: link.snapshot?.state ?? null,
129 title: link.snapshot?.title ?? null,
130 headBranch: link.snapshot?.headBranch ?? null,
131 baseBranch: link.snapshot?.baseBranch ?? null,
132 isDraft: link.snapshot?.isDraft ?? null,
133 stack,
134 };
136​
137export function listThreadPullRequests(
138 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
139): ListThreadPullRequestsResult {
140 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
141 return {
142 pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) =>
143 entryOf(link, chains),
144 ),
145 chains: chains.map((chain) => ({
146 kind: chain.kind,
147 numbers: chain.layers.map((layer) => layer.number),
148 })),
149 };
151​
152function projectForPullRequest(
153 projects: ReadonlyArray<OrchestrationProjectShell>,
154 target: { readonly host: string; readonly repository: string },
155 preferred: OrchestrationProjectShell | undefined,
156): OrchestrationProjectShell | undefined {
157 // The same rule the guide service uses: a pull request reads through a project whose checkout
158 // names it with the same host-level key, which also maps Azure DevOps' org/project/_git/repo.
159 const matches = (project: OrchestrationProjectShell) => {
160 const own = pullRequestSyncKey(
161 { projectId: project.id, host: target.host, repository: target.repository, number: 1 },
162 project.repositoryIdentity ?? undefined,
163 );
164 const projectKey =
165 project.repositoryIdentity == null
166 ? null
167 : pullRequestSyncKey(
168 {
169 projectId: project.id,
170 repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? "",
171 number: 1,
172 },
173 project.repositoryIdentity,
174 );
175 return (
176 own !== null &&
177 projectKey !== null &&
178 own.host === projectKey.host &&
179 own.repository === projectKey.repository
180 );
181 };
182 if (preferred !== undefined && matches(preferred)) return preferred;
183 return projects.find(matches);
185​
186const make = Effect.gen(function* () {
187 const engine = yield* Orchestrator.OrchestratorV2;
188 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
189​
190 const projects = yield* ProjectService.ProjectService;
191 const crypto = yield* Crypto.Crypto;
192​
193 const commandId = (tag: string, threadId: ThreadId) =>
194 crypto.randomUUIDv4().pipe(
195 Effect.orDie,
196 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
197 );
198​
199 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
200 Failure:
201 | typeof PullRequestLinkFailedError
202 | typeof PullRequestUnlinkFailedError
203 | typeof PullRequestListFailedError
204 | typeof PullRequestWatchFailedError,
205 requested: ThreadId | undefined,
206 ) {
207 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
208 const threadId = requested ?? scope.thread?.threadId;
209 if (threadId === undefined) {
210 return yield* new PullRequestThreadRequiredError();
211 }
212 const thread = yield* engine
213 .getThreadShell(threadId)
214 .pipe(Effect.map(Option.fromNullishOr))
215 .pipe(Effect.mapError((cause) => new Failure({ cause })));
216 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
217 return yield* new PullRequestThreadNotFoundError({ threadId });
218 }
219 return thread.value;
220 });
221​
222 const projectOf = (
223 thread: OrchestrationV2ThreadShell,
224 Failure:
225 | typeof PullRequestLinkFailedError
226 | typeof PullRequestUnlinkFailedError
227 | typeof PullRequestWatchFailedError,
228 ) =>
229 projects.getShell(thread.projectId).pipe(
230 Effect.map(Option.getOrUndefined),
231 Effect.mapError((cause) => new Failure({ cause })),
232 );
233​
234 const dispatchFailure =
235 (
236 Failure:
237 | typeof PullRequestLinkFailedError
238 | typeof PullRequestUnlinkFailedError
239 | typeof PullRequestWatchFailedError,
240 ) =>
241 <E>(
242 cause: Cause.Cause<E>,
243 ): Effect.Effect<
244 never,
245 PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError
246 > =>
247 Cause.hasInterruptsOnly(cause)
248 ? Effect.failCause(cause as Cause.Cause<never>)
249 : Effect.fail(new Failure({ cause }));
250​
251 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (
252 input: PullRequestTargetInput,
253 watching: boolean,
254 ) {
255 const thread = yield* requireThread(PullRequestWatchFailedError, input.threadId);
256 const project = yield* projectOf(thread, PullRequestWatchFailedError);
257 const target = yield* resolveTarget(input, project);
258 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
259 threadPullRequestsOf(shell).find(
260 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
261 );
262 if (watching && thread.lineage.relationshipToParent === "subagent") {
263 return yield* new PullRequestWatchFromSubagentError();
264 }
265 const before = watchedLink(thread);
266 if (watching && before?.snapshot?.state === "merged") {
267 return yield* new PullRequestNotOpenError({ state: "merged" });
268 }
269 yield* engine
270 .dispatch({
271 type: "thread.pull-request.watch",
272 commandId: yield* commandId("mcp-pr-watch", thread.id),
273 threadId: thread.id,
274 host: target.host,
275 repository: target.repository,
276 number: target.number,
277 watching,
278 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
279 })
280 .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));
281 const after = yield* requireThread(PullRequestWatchFailedError, thread.id);
282 return {
283 host: target.host,
284 repository: target.repository,
285 number: target.number,
286 url: target.url,
287 watching: watchedLink(after)?.watch !== undefined,
288 wasWatching: before?.watch !== undefined,
289 };
290 });
291​
292 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
293 targets: ReadonlyArray<Omit<PullRequestTargetInput, "threadId">>,
294 ) {
295 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
296 const callerThread =
297 scope.thread === undefined
298 ? undefined
299 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
300 Effect.orElseSucceed(() => null),
301 Effect.map((shell) => shell ?? undefined),
302 );
303 const known = yield* projects
304 .listShells()
305 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
306 const callerProject = known.find((project) => project.id === callerThread?.projectId);
307 return yield* Effect.forEach(targets, (input) =>
308 resolveTarget(input, callerProject).pipe(
309 Effect.map((target) => ({
310 input,
311 target,
312 project: projectForPullRequest(known, target, callerProject),
313 failure: null,
314 })),
315 Effect.catch((error) =>
316 Effect.succeed({ input, target: null, project: undefined, failure: error.message }),
317 ),
318 ),
319 );
320 });
321​
322 const guideReference = (
323 project: OrchestrationProjectShell,
324 target: { readonly host: string; readonly repository: string; readonly number: number },
325 ) => ({
326 projectId: project.id,
327 host: target.host,
328 repository: target.repository,
329 number: target.number,
330 });
331​
332 const guideFailureDetail = (error: { readonly message: string }) =>
333 "detail" in error && typeof error.detail === "string" ? error.detail : error.message;
334​
335 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
336 handle: (params: P) => Effect.Effect<A, E, R>,
337 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
338​
339 return {
340 link_pull_request: writesThread((input) =>
341 Effect.gen(function* () {
342 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
343 const project = yield* projectOf(thread, PullRequestLinkFailedError);
344 const target = yield* resolveTarget(input, project);
345 const existing = threadPullRequestsOf(thread).find((link) =>
346 threadPullRequestKeysEqual(link, target),
347 );
348 if (existing && existing.source !== "stack-dismissed")
349 return { ...target, alreadyLinked: true };
350 const alreadyLinked = yield* engine
351 .dispatch({
352 type: "thread.pull-request.link",
353 commandId: yield* commandId("mcp-pr-link", thread.id),
354 threadId: thread.id,
355 host: target.host,
356 repository: target.repository,
357 number: target.number,
358 url: target.url,
359 source: "agent",
360 })
361 .pipe(
362 Effect.as(false),
363​
364 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
365 );
366 return { ...target, alreadyLinked };
367 }),
368 ),
369 unlink_pull_request: writesThread((input) =>
370 Effect.gen(function* () {
371 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
372 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
373 const target = yield* resolveTarget(input, project);
374 if (!threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, target)))
375 return {
376 host: target.host,
377 repository: target.repository,
378 number: target.number,
379 wasLinked: false,
380 };
381 const wasLinked = yield* engine
382 .dispatch({
383 type: "thread.pull-request.unlink",
384 commandId: yield* commandId("mcp-pr-unlink", thread.id),
385 threadId: thread.id,
386 host: target.host,
387 repository: target.repository,
388 number: target.number,
389 })
390 .pipe(
391 Effect.as(true),
392​
393 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
394 );
395 return {
396 host: target.host,
397 repository: target.repository,
398 number: target.number,
399 wasLinked,
400 };
401 }),
402 ),
403 list_thread_pull_requests: McpToolAccess.reads((input) =>
404 requireThread(PullRequestListFailedError, input.threadId).pipe(
405 Effect.map(listThreadPullRequests),
406 ),
407 ),
408 watch_pull_request: writesThread((input) => setWatching(input, true)),
409 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
410 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
411 Effect.gen(function* () {
412 const located = yield* locateAll(input.pullRequests);
413 const guides = yield* Effect.forEach(
414 located,
415 (entry) =>
416 Effect.gen(function* () {
417 if (entry.target === null) {
418 return {
419 host: entry.input.host ?? "",
420 repository: entry.input.repository ?? "",
421 number: entry.input.number ?? 0,
422 url: entry.input.url ?? "",
423 outcome: "failed" as const,
424 detail: entry.failure,
425 };
426 }
427 const identity = {
428 host: entry.target.host,
429 repository: entry.target.repository,
430 number: entry.target.number,
431 url: entry.target.url,
432 };
433 if (entry.project === undefined) {
434 return {
435 ...identity,
436 outcome: "failed" as const,
437 detail: new PullRequestProjectNotFoundError({
438 repository: entry.target.repository,
439 }).message,
440 };
441 }
442 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
443 Effect.map((result) => ({
444 ...identity,
445 outcome: result.started ? ("started" as const) : ("running" as const),
446 detail: null,
447 })),
448 Effect.catch((error) =>
449 Effect.succeed({
450 ...identity,
451 outcome: "failed" as const,
452 detail: guideFailureDetail(error),
453 }),
454 ),
455 );
456 }),
457 { concurrency: 4 },
458 );
459 return { guides };
460 }),
461 ),
462 read_pull_request_guide: McpToolAccess.reads((input) =>
463 Effect.gen(function* () {
464 const [entry] = yield* locateAll([input]);
465 if (entry !== undefined && entry.target === null) {
466 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
467 }
468 if (entry === undefined || entry.target === null || entry.project === undefined) {
469 return yield* new PullRequestProjectNotFoundError({
470 repository: entry?.target.repository ?? input.repository ?? "",
471 });
472 }
473 const result = yield* reviewGuides.get(guideReference(entry.project, entry.target)).pipe(
474 Effect.mapError(
475 (error) =>
476 new PullRequestGuideFailedError({
477 detail: guideFailureDetail(error),
478 cause: error,
479 }),
480 ),
481 );
482 return {
483 host: entry.target.host,
484 repository: entry.target.repository,
485 number: entry.target.number,
486 url: entry.target.url,
487 guide: result.guide,
488 run: result.run,
489 currentHeadSha: result.currentHeadSha,
490 stale:
491 result.guide !== null &&
492 result.currentHeadSha !== null &&
493 result.guide.headSha !== result.currentHeadSha,
494 };
495 }),
496 ),
497 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
498});
499​
500export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);