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

handlers.ts

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