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

handlers.ts

615 lines23.0 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 SecureRandom from "effect/crypto/SecureRandom";
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 { threadNotFound } from "../../threadAccess.ts";
31import {
32 type ListThreadPullRequestsResult,
33 PullRequestLinkFailedError,
34 PullRequestUrlInvalidError,
35 PullRequestTargetIncompleteError,
36 PullRequestHostRequiredError,
37 PullRequestUrlUnavailableError,
38 PullRequestUnlinkFailedError,
39 PullRequestListFailedError,
40 PullRequestNotOpenError,
41 type PullRequestTargetInput,
42 PullRequestWatchFailedError,
43 PullRequestWatchFromSubagentError,
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 random = yield* SecureRandom.SecureRandom;
204​
205 const commandId = (tag: string, threadId: ThreadId) =>
206 random.uuidV4().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* threadNotFound(engine, threadId, `Thread ${threadId} was not found.`);
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 (
450 !threadPullRequestsOf(thread).some(
451 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
452 )
453 )
454 return {
455 host: target.host,
456 repository: target.repository,
457 number: target.number,
458 wasLinked: false,
459 };
460 const wasLinked = yield* engine
461 .dispatch({
462 type: "thread.pull-request.unlink",
463 commandId: yield* commandId("mcp-pr-unlink", thread.id),
464 threadId: thread.id,
465 host: target.host,
466 repository: target.repository,
467 number: target.number,
468 })
469 .pipe(
470 Effect.as(true),
471​
472 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
473 );
474 return {
475 host: target.host,
476 repository: target.repository,
477 number: target.number,
478 wasLinked,
479 };
480 }),
481 ),
482 unlink_pull_requests: writesThread((input) =>
483 Effect.gen(function* () {
484 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
485 const visible = visibleThreadPullRequests(threadPullRequestsOf(thread));
486 const matching = visible.flatMap((link) => {
487 const state = link.snapshot?.state;
488 return state !== undefined && input.states.includes(state)
489 ? [{ ...normalizeThreadPullRequestKey(link), state }]
490 : [];
491 });
492 yield* Effect.forEach(matching, ({ host, repository, number }) =>
493 Effect.gen(function* () {
494 yield* engine.dispatch({
495 type: "thread.pull-request.unlink",
496 commandId: yield* commandId("mcp-pr-unlink", thread.id),
497 threadId: thread.id,
498 host,
499 repository,
500 number,
501 });
502 }).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))),
503 );
504 // Numbers grouped by repository and state keep a large batch's result small.
505 const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`);
506 return {
507 unlinked: [...groups.values()].map((prs) => ({
508 host: prs[0]!.host,
509 repository: prs[0]!.repository,
510 state: prs[0]!.state,
511 numbers: prs.map((pr) => pr.number),
512 })),
513 unlinkedCount: matching.length,
514 remaining: visible.length - matching.length,
515 };
516 }),
517 ),
518 list_thread_pull_requests: McpToolAccess.reads((input) =>
519 requireThread(PullRequestListFailedError, input.threadId).pipe(
520 Effect.map(listThreadPullRequests),
521 ),
522 ),
523 watch_pull_request: writesThread((input) => setWatching(input, true)),
524 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
525 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
526 Effect.gen(function* () {
527 const located = yield* locateAll(input.pullRequests);
528 const guides = yield* Effect.forEach(
529 located,
530 (entry) =>
531 Effect.gen(function* () {
532 if (entry.target === null) {
533 return {
534 host: entry.input.host ?? "",
535 repository: entry.input.repository ?? "",
536 number: entry.input.number ?? 0,
537 url: entry.input.url ?? "",
538 outcome: "failed" as const,
539 detail: entry.failure,
540 };
541 }
542 const identity = {
543 host: entry.target.host,
544 repository: entry.target.repository,
545 number: entry.target.number,
546 url: entry.target.url,
547 };
548 if (entry.project === undefined) {
549 return {
550 ...identity,
551 outcome: "failed" as const,
552 detail: new PullRequestProjectNotFoundError({
553 repository: entry.target.repository,
554 }).message,
555 };
556 }
557 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
558 Effect.map((result) => ({
559 ...identity,
560 outcome: result.started ? ("started" as const) : ("running" as const),
561 detail: null,
562 })),
563 Effect.catch((error) =>
564 Effect.succeed({
565 ...identity,
566 outcome: "failed" as const,
567 detail: guideFailureDetail(error),
568 }),
569 ),
570 );
571 }),
572 { concurrency: 4 },
573 );
574 return { guides };
575 }),
576 ),
577 read_pull_request_guide: McpToolAccess.reads((input) =>
578 Effect.gen(function* () {
579 const [entry] = yield* locateAll([input]);
580 if (entry !== undefined && entry.target === null) {
581 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
582 }
583 if (entry === undefined || entry.target === null || entry.project === undefined) {
584 return yield* new PullRequestProjectNotFoundError({
585 repository: entry?.target.repository ?? input.repository ?? "",
586 });
587 }
588 const result = yield* reviewGuides.get(guideReference(entry.project, entry.target)).pipe(
589 Effect.mapError(
590 (error) =>
591 new PullRequestGuideFailedError({
592 detail: guideFailureDetail(error),
593 cause: error,
594 }),
595 ),
596 );
597 return {
598 host: entry.target.host,
599 repository: entry.target.repository,
600 number: entry.target.number,
601 url: entry.target.url,
602 guide: result.guide,
603 run: result.run,
604 currentHeadSha: result.currentHeadSha,
605 stale:
606 result.guide !== null &&
607 result.currentHeadSha !== null &&
608 result.guide.headSha !== result.currentHeadSha,
609 };
610 }),
611 ),
612 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
613});
614​
615export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);