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

handlers.ts

527 lines20.5 KB

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