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

handlers.ts

611 lines22.8 KB

1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 type OrchestrationV2ThreadShell,
5 type SourceControlProviderKind,
6 type ThreadId,
7 type ThreadPullRequestLink,
8} from "@t3tools/contracts";
9import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry";
10import * as Cause from "effect/Cause";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14​
15import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
16import * as ProjectService from "../../../project/ProjectService.ts";
17import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
18import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
19import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
20import {
21 normalizeThreadPullRequestKey,
22 resolveThreadPullRequestChains,
23 threadPullRequestKeyOf,
24 threadPullRequestKeysEqual,
25 threadPullRequestsOf,
26 visibleThreadPullRequests,
27} from "../../../sourceControl/threadPullRequests.ts";
28import * as McpInvocationContext from "../../McpInvocationContext.ts";
29import * as McpToolAccess from "../../McpToolAccess.ts";
30import {
31 type ListThreadPullRequestsResult,
32 PullRequestLinkFailedError,
33 PullRequestUrlInvalidError,
34 PullRequestTargetIncompleteError,
35 PullRequestHostRequiredError,
36 PullRequestUrlUnavailableError,
37 PullRequestUnlinkFailedError,
38 PullRequestListFailedError,
39 PullRequestNotOpenError,
40 type PullRequestTargetInput,
41 PullRequestWatchFailedError,
42 PullRequestWatchFromSubagentError,
43 PullRequestThreadNotFoundError,
44 PullRequestThreadRequiredError,
45 PullRequestGuideFailedError,
46 PullRequestProjectNotFoundError,
47 PullRequestsToolkit,
48 type ThreadPullRequestEntry,
49 CHILD_PULL_REQUEST_REPORT_NEXT,
50} from "./tools.ts";
51​
52interface ResolvedTarget {
53 readonly host: string;
54 readonly repository: string;
55 readonly number: number;
56 readonly url: string;
58​
59function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
60 readonly host: string | null;
61 readonly kind: SourceControlProviderKind | null;
62} {
63 const identity = project?.repositoryIdentity;
64 const kind = identity?.provider ?? null;
65 if (!identity || kind === null) return { host: null, kind: null };
66 return {
67 host: sourceControlDefinitions.changeRequestHost(identity, kind),
68 kind,
69 };
71​
72const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
73 input: PullRequestTargetInput,
74 project: OrchestrationProjectShell | undefined,
75) {
76 if (input.url !== undefined) {
77 const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link;
78 if (parsed === undefined) {
79 return yield* new PullRequestUrlInvalidError({});
80 }
81 return {
82 ...normalizeThreadPullRequestKey(parsed),
83 url: canonicalizeGitCafePullRequestUrl(input.url),
84 } satisfies ResolvedTarget;
85 }
86 if (input.repository === undefined || input.number === undefined) {
87 return yield* new PullRequestTargetIncompleteError({});
88 }
89 const projectHost = projectHostAndProvider(project);
90 const host = (input.host ?? projectHost.host)?.toLowerCase();
91 if (host === undefined) {
92 return yield* new PullRequestHostRequiredError({});
93 }
94 const repository = input.repository.toLowerCase();
95 // Without a URL, a public forge host says what shape its change request URLs take;
96 // any other host is taken to run the project's own forge.
97 const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind;
98 const kind =
99 sourceControlDefinitions.findByPublicHost(host)?.kind ??
100 (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind);
101 const url =
102 kind === null
103 ? null
104 : sourceControlDefinitions.get(kind).changeRequestUrl({
105 host,
106 repository,
107 number: input.number,
108 remoteUrl: project?.repositoryIdentity?.locator.remoteUrl,
109 });
110 if (url === null) {
111 return yield* new PullRequestUrlUnavailableError({});
112 }
113 return {
114 ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
115 url: canonicalizeGitCafePullRequestUrl(url),
116 } satisfies ResolvedTarget;
117});
118​
119function entryOf(
120 link: ThreadPullRequestLink,
121 chains: ReturnType<typeof resolveThreadPullRequestChains>,
122): ThreadPullRequestEntry {
123 const key = threadPullRequestKeyOf(link);
124 let stack: ThreadPullRequestEntry["stack"] = null;
125 for (const chain of chains) {
126 if (chain.layers.length < 2) continue;
127 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
128 if (index !== -1) {
129 stack = { kind: chain.kind, position: chain.depths[index]! + 1, size: chain.layers.length };
130 break;
131 }
132 }
133 return {
134 host: normalizeThreadPullRequestKey(link).host,
135 repository: link.repository,
136 number: link.number,
137 url: link.url,
138 source: link.source,
139 watching: link.watch !== undefined,
140 state: link.snapshot?.state ?? null,
141 title: link.snapshot?.title ?? null,
142 headBranch: link.snapshot?.headBranch ?? null,
143 baseBranch: link.snapshot?.baseBranch ?? null,
144 isDraft: link.snapshot?.isDraft ?? null,
145 stack,
146 };
148​
149export function listThreadPullRequests(
150 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
151): ListThreadPullRequestsResult {
152 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
153 return {
154 pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) =>
155 entryOf(link, chains),
156 ),
157 chains: chains.map((chain) => ({
158 kind: chain.kind,
159 numbers: chain.layers.map((layer) => layer.number),
160 })),
161 };
163​
164function projectForPullRequest(
165 projects: ReadonlyArray<OrchestrationProjectShell>,
166 target: { readonly host: string; readonly repository: string },
167 preferred: OrchestrationProjectShell | undefined,
168): OrchestrationProjectShell | undefined {
169 // Match the guide service's host-level repository key, including Azure DevOps org/project/_git/repo.
170 const matches = (project: OrchestrationProjectShell) => {
171 const own = pullRequestSyncKey(
172 { projectId: project.id, host: target.host, repository: target.repository, number: 1 },
173 project.repositoryIdentity ?? undefined,
174 );
175 const projectKey =
176 project.repositoryIdentity == null
177 ? null
178 : pullRequestSyncKey(
179 {
180 projectId: project.id,
181 repository:
182 sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? "",
183 number: 1,
184 },
185 project.repositoryIdentity,
186 );
187 return (
188 own !== null &&
189 projectKey !== null &&
190 own.host === projectKey.host &&
191 own.repository === projectKey.repository
192 );
193 };
194 if (preferred !== undefined && matches(preferred)) return preferred;
195 return projects.find(matches);
197​
198const make = Effect.gen(function* () {
199 const engine = yield* Orchestrator.OrchestratorV2;
200 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
201​
202 const projects = yield* ProjectService.ProjectService;
203 const crypto = yield* Crypto.Crypto;
204​
205 const commandId = (tag: string, threadId: ThreadId) =>
206 crypto.randomUUIDv4().pipe(
207 Effect.orDie,
208 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
209 );
210​
211 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
212 Failure:
213 | typeof PullRequestLinkFailedError
214 | typeof PullRequestUnlinkFailedError
215 | typeof PullRequestListFailedError
216 | typeof PullRequestWatchFailedError,
217 requested: ThreadId | undefined,
218 ) {
219 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
220 const threadId = requested ?? scope.thread?.threadId;
221 if (threadId === undefined) {
222 return yield* new PullRequestThreadRequiredError();
223 }
224 const thread = yield* engine.getThreadShell(threadId).pipe(
225 Effect.map(Option.fromNullishOr),
226 Effect.mapError((cause) => new Failure({ cause })),
227 );
228 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
229 return yield* new PullRequestThreadNotFoundError({ threadId });
230 }
231 return thread.value;
232 });
233​
234 const projectOf = (
235 thread: OrchestrationV2ThreadShell,
236 Failure:
237 | typeof PullRequestLinkFailedError
238 | typeof PullRequestUnlinkFailedError
239 | typeof PullRequestWatchFailedError,
240 ) =>
241 projects.getShell(thread.projectId).pipe(
242 Effect.map(Option.getOrUndefined),
243 Effect.mapError((cause) => new Failure({ cause })),
244 );
245​
246 const dispatchFailure =
247 (
248 Failure:
249 | typeof PullRequestLinkFailedError
250 | typeof PullRequestUnlinkFailedError
251 | typeof PullRequestWatchFailedError,
252 ) =>
253 <E>(
254 cause: Cause.Cause<E>,
255 ): Effect.Effect<
256 never,
257 PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError
258 > =>
259 Cause.hasInterruptsOnly(cause)
260 ? Effect.failCause(cause as Cause.Cause<never>)
261 : Effect.fail(new Failure({ cause }));
262​
263 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (
264 input: PullRequestTargetInput,
265 watching: boolean,
266 ) {
267 const thread = yield* requireThread(PullRequestWatchFailedError, input.threadId);
268 const project = yield* projectOf(thread, PullRequestWatchFailedError);
269 const target = yield* resolveTarget(input, project);
270 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
271 threadPullRequestsOf(shell).find(
272 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
273 );
274 if (watching && thread.lineage.relationshipToParent === "subagent") {
275 return yield* new PullRequestWatchFromSubagentError();
276 }
277 const before = watchedLink(thread);
278 if (watching && before?.snapshot?.state === "merged") {
279 return yield* new PullRequestNotOpenError({ state: "merged" });
280 }
281 yield* engine
282 .dispatch({
283 type: "thread.pull-request.watch",
284 commandId: yield* commandId("mcp-pr-watch", thread.id),
285 threadId: thread.id,
286 host: target.host,
287 repository: target.repository,
288 number: target.number,
289 watching,
290 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
291 })
292 .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));
293 const after = yield* requireThread(PullRequestWatchFailedError, thread.id);
294 return {
295 host: target.host,
296 repository: target.repository,
297 number: target.number,
298 url: target.url,
299 watching: watchedLink(after)?.watch !== undefined,
300 wasWatching: before?.watch !== undefined,
301 };
302 });
303​
304 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
305 targets: ReadonlyArray<Omit<PullRequestTargetInput, "threadId">>,
306 ) {
307 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
308 const callerThread =
309 scope.thread === undefined
310 ? undefined
311 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
312 Effect.orElseSucceed(() => null),
313 Effect.map((shell) => shell ?? undefined),
314 );
315 const known = yield* projects
316 .listShells()
317 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
318 const callerProject = known.find((project) => project.id === callerThread?.projectId);
319 // A pull request named by host and repository builds its URL through the project that holds
320 // it, which need not be the caller's.
321 const urlProject = (input: PullRequestTargetInput) =>
322 input.url === undefined && input.host !== undefined && input.repository !== undefined
323 ? (projectForPullRequest(
324 known,
325 { host: input.host, repository: input.repository },
326 callerProject,
327 ) ?? callerProject)
328 : callerProject;
329 return yield* Effect.forEach(targets, (input) =>
330 resolveTarget(input, urlProject(input)).pipe(
331 Effect.map((target) => ({
332 input,
333 target,
334 project: projectForPullRequest(known, target, callerProject),
335 failure: null,
336 })),
337 Effect.catch((error) =>
338 Effect.succeed({ input, target: null, project: undefined, failure: error.message }),
339 ),
340 ),
341 );
342 });
343​
344 const guideReference = (
345 project: OrchestrationProjectShell,
346 target: { readonly host: string; readonly repository: string; readonly number: number },
347 ) => ({
348 projectId: project.id,
349 host: target.host,
350 repository: target.repository,
351 number: target.number,
352 });
353​
354 const guideFailureDetail = (error: { readonly message: string }) =>
355 "detail" in error && typeof error.detail === "string" ? error.detail : error.message;
356​
357 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
358 handle: (params: P) => Effect.Effect<A, E, R>,
359 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
360​
361 return {
362 link_pull_request: writesThread((input) =>
363 Effect.gen(function* () {
364 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
365 const next =
366 thread.lineage.relationshipToParent === "subagent"
367 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
368 : {};
369 const project = yield* projectOf(thread, PullRequestLinkFailedError);
370 const target = yield* resolveTarget(input, project);
371 const existing = threadPullRequestsOf(thread).find((link) =>
372 threadPullRequestKeysEqual(link, target),
373 );
374 if (existing && existing.source !== "stack-dismissed")
375 return { ...target, alreadyLinked: true, ...next };
376 const alreadyLinked = yield* engine
377 .dispatch({
378 type: "thread.pull-request.link",
379 commandId: yield* commandId("mcp-pr-link", thread.id),
380 threadId: thread.id,
381 host: target.host,
382 repository: target.repository,
383 number: target.number,
384 url: target.url,
385 source: "agent",
386 })
387 .pipe(
388 Effect.as(false),
389​
390 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
391 );
392 return { ...target, alreadyLinked, ...next };
393 }),
394 ),
395 link_pull_requests: writesThread((input) =>
396 Effect.gen(function* () {
397 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
398 const targets: Array<ResolvedTarget> = [];
399 const invalidUrls: Array<string> = [];
400 for (const url of input.urls) {
401 const target = yield* resolveTarget({ url }, undefined).pipe(Effect.option);
402 if (Option.isNone(target)) invalidUrls.push(url);
403 else if (!targets.some((seen) => threadPullRequestKeysEqual(seen, target.value)))
404 targets.push(target.value);
405 }
406 const links = threadPullRequestsOf(thread);
407 const isLinked = (target: ResolvedTarget) =>
408 links.some(
409 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
410 );
411 const fresh = targets.filter((target) => !isLinked(target));
412 const alreadyLinked = targets.filter(isLinked);
413 yield* Effect.forEach(fresh, (target) =>
414 Effect.gen(function* () {
415 yield* engine.dispatch({
416 type: "thread.pull-request.link",
417 commandId: yield* commandId("mcp-pr-link", thread.id),
418 threadId: thread.id,
419 host: target.host,
420 repository: target.repository,
421 number: target.number,
422 url: target.url,
423 source: "agent",
424 });
425 }).pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError))),
426 );
427 const byRepository = (prs: ReadonlyArray<ResolvedTarget>) =>
428 [...Map.groupBy(prs, (pr) => `${pr.host}/${pr.repository}`).values()].map((group) => ({
429 host: group[0]!.host,
430 repository: group[0]!.repository,
431 numbers: group.map((pr) => pr.number),
432 }));
433 return {
434 linked: byRepository(fresh),
435 alreadyLinked: byRepository(alreadyLinked),
436 linkedCount: targets.length,
437 ...(invalidUrls.length > 0 ? { invalidUrls } : {}),
438 ...(thread.lineage.relationshipToParent === "subagent"
439 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
440 : {}),
441 };
442 }),
443 ),
444 unlink_pull_request: writesThread((input) =>
445 Effect.gen(function* () {
446 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
447 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
448 const target = yield* resolveTarget(input, project);
449 if (!threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, target)))
450 return {
451 host: target.host,
452 repository: target.repository,
453 number: target.number,
454 wasLinked: false,
455 };
456 const wasLinked = yield* engine
457 .dispatch({
458 type: "thread.pull-request.unlink",
459 commandId: yield* commandId("mcp-pr-unlink", thread.id),
460 threadId: thread.id,
461 host: target.host,
462 repository: target.repository,
463 number: target.number,
464 })
465 .pipe(
466 Effect.as(true),
467​
468 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
469 );
470 return {
471 host: target.host,
472 repository: target.repository,
473 number: target.number,
474 wasLinked,
475 };
476 }),
477 ),
478 unlink_pull_requests: writesThread((input) =>
479 Effect.gen(function* () {
480 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
481 const visible = visibleThreadPullRequests(threadPullRequestsOf(thread));
482 const matching = visible.flatMap((link) => {
483 const state = link.snapshot?.state;
484 return state !== undefined && input.states.includes(state)
485 ? [{ ...normalizeThreadPullRequestKey(link), state }]
486 : [];
487 });
488 yield* Effect.forEach(matching, ({ host, repository, number }) =>
489 Effect.gen(function* () {
490 yield* engine.dispatch({
491 type: "thread.pull-request.unlink",
492 commandId: yield* commandId("mcp-pr-unlink", thread.id),
493 threadId: thread.id,
494 host,
495 repository,
496 number,
497 });
498 }).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))),
499 );
500 // Numbers grouped by repository and state keep a large batch's result small.
501 const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`);
502 return {
503 unlinked: [...groups.values()].map((prs) => ({
504 host: prs[0]!.host,
505 repository: prs[0]!.repository,
506 state: prs[0]!.state,
507 numbers: prs.map((pr) => pr.number),
508 })),
509 unlinkedCount: matching.length,
510 remaining: visible.length - matching.length,
511 };
512 }),
513 ),
514 list_thread_pull_requests: McpToolAccess.reads((input) =>
515 requireThread(PullRequestListFailedError, input.threadId).pipe(
516 Effect.map(listThreadPullRequests),
517 ),
518 ),
519 watch_pull_request: writesThread((input) => setWatching(input, true)),
520 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
521 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
522 Effect.gen(function* () {
523 const located = yield* locateAll(input.pullRequests);
524 const guides = yield* Effect.forEach(
525 located,
526 (entry) =>
527 Effect.gen(function* () {
528 if (entry.target === null) {
529 return {
530 host: entry.input.host ?? "",
531 repository: entry.input.repository ?? "",
532 number: entry.input.number ?? 0,
533 url: entry.input.url ?? "",
534 outcome: "failed" as const,
535 detail: entry.failure,
536 };
537 }
538 const identity = {
539 host: entry.target.host,
540 repository: entry.target.repository,
541 number: entry.target.number,
542 url: entry.target.url,
543 };
544 if (entry.project === undefined) {
545 return {
546 ...identity,
547 outcome: "failed" as const,
548 detail: new PullRequestProjectNotFoundError({
549 repository: entry.target.repository,
550 }).message,
551 };
552 }
553 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
554 Effect.map((result) => ({
555 ...identity,
556 outcome: result.started ? ("started" as const) : ("running" as const),
557 detail: null,
558 })),
559 Effect.catch((error) =>
560 Effect.succeed({
561 ...identity,
562 outcome: "failed" as const,
563 detail: guideFailureDetail(error),
564 }),
565 ),
566 );
567 }),
568 { concurrency: 4 },
569 );
570 return { guides };
571 }),
572 ),
573 read_pull_request_guide: McpToolAccess.reads((input) =>
574 Effect.gen(function* () {
575 const [entry] = yield* locateAll([input]);
576 if (entry !== undefined && entry.target === null) {
577 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
578 }
579 if (entry === undefined || entry.target === null || entry.project === undefined) {
580 return yield* new PullRequestProjectNotFoundError({
581 repository: entry?.target.repository ?? input.repository ?? "",
582 });
583 }
584 const result = yield* reviewGuides.get(guideReference(entry.project, entry.target)).pipe(
585 Effect.mapError(
586 (error) =>
587 new PullRequestGuideFailedError({
588 detail: guideFailureDetail(error),
589 cause: error,
590 }),
591 ),
592 );
593 return {
594 host: entry.target.host,
595 repository: entry.target.repository,
596 number: entry.target.number,
597 url: entry.target.url,
598 guide: result.guide,
599 run: result.run,
600 currentHeadSha: result.currentHeadSha,
601 stale:
602 result.guide !== null &&
603 result.currentHeadSha !== null &&
604 result.guide.headSha !== result.currentHeadSha,
605 };
606 }),
607 ),
608 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
609});
610​
611export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);