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

handlers.ts

1,221 lines48.5 KB

1import {
2 CommandId,
3 NonNegativeInt,
4 type PullRequestActivity,
5 PullRequestListCursors,
6 type PullRequestRef,
7 type PullRequestReviewCommentDraft,
8 type PullRequestReviewThread,
9 type OrchestrationProjectShell,
10 type PullRequestState,
11 type PullRequestWatchUntil,
12 type OrchestrationV2ThreadShell,
13 type ThreadId,
14 type ThreadPullRequestLink,
15 TrimmedNonEmptyString,
16} from "@t3tools/contracts";
17import * as Cause from "effect/Cause";
18import * as SecureRandom from "effect/crypto/SecureRandom";
19import * as Effect from "effect/Effect";
20import * as Base64Url from "effect/encoding/Base64Url";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23​
24import * as GitManager from "../../../git/GitManager.ts";
25import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
26import * as ProjectService from "../../../project/ProjectService.ts";
27import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
28import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts";
29import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
30import * as PullRequestService from "../../../pullRequest/PullRequestService.ts";
31import { reviewPositionInPatch } from "../../../pullRequest/pullRequestReviewPosition.ts";
32import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
33import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
34import {
35 normalizeThreadPullRequestKey,
36 resolveThreadPullRequestChains,
37 threadPullRequestKeyOf,
38 threadPullRequestKeysEqual,
39 threadPullRequestsOf,
40 visibleThreadPullRequests,
41} from "../../../sourceControl/threadPullRequests.ts";
42import * as McpInvocationContext from "../../McpInvocationContext.ts";
43import * as McpToolAccess from "../../McpToolAccess.ts";
44import { threadNotFound } from "../../threadAccess.ts";
45import {
46 type ListThreadPullRequestsResult,
47 PullRequestBranchHasNoneError,
48 PullRequestCursorInvalidError,
49 PullRequestForgeError,
50 PullRequestNothingToDoError,
51 type PullRequestReadSection,
52 type ReadPullRequestResult,
53 type ReviewLineComment,
54 type ThreadPullRequestInput,
55 PullRequestLinkFailedError,
56 PullRequestUnlinkFailedError,
57 PullRequestListFailedError,
58 type PullRequestTargetInput,
59 PullRequestThreadRequiredError,
60 PullRequestGuideFailedError,
61 PullRequestProjectNotFoundError,
62 PullRequestsToolkit,
63 type ThreadPullRequestEntry,
64 CHILD_PULL_REQUEST_REPORT_NEXT,
65} from "./tools.ts";
66​
67const ReadCursor = Schema.Union([
68 Schema.Struct({ diff: TrimmedNonEmptyString }),
69 Schema.Struct({
70 threads: NonNegativeInt,
71 comments: NonNegativeInt,
72 includeResolved: Schema.Boolean,
73 }),
74]);
75type ReadCursor = typeof ReadCursor.Type;
76​
77const ReadCursorJson = Schema.fromJsonString(ReadCursor);
78const ListCursorsJson = Schema.fromJsonString(PullRequestListCursors);
79const encodeReadCursorJson = Schema.encodeSync(ReadCursorJson);
80const encodeListCursorsJson = Schema.encodeSync(ListCursorsJson);
81const decodeReadCursorJson = Schema.decodeUnknownEffect(ReadCursorJson);
82const decodeListCursorsJson = Schema.decodeUnknownEffect(ListCursorsJson);
83​
84const decodeCursorText = (cursor: string) =>
85 Effect.fromResult(Base64Url.decodeString(cursor)).pipe(
86 Effect.mapError(() => new PullRequestCursorInvalidError({})),
87 );
88​
89const readCursors = {
90 encode: (value: ReadCursor) => Base64Url.encode(encodeReadCursorJson(value)),
91 decode: (cursor: string) =>
92 decodeCursorText(cursor).pipe(
93 Effect.flatMap(decodeReadCursorJson),
94 Effect.mapError(() => new PullRequestCursorInvalidError({})),
95 ),
96};
97​
98const listCursors = {
99 encode: (value: PullRequestListCursors) => Base64Url.encode(encodeListCursorsJson(value)),
100 decode: (cursor: string) =>
101 decodeCursorText(cursor).pipe(
102 Effect.flatMap(decodeListCursorsJson),
103 Effect.mapError(() => new PullRequestCursorInvalidError({})),
104 ),
105};
106​
107/** Keeps one conversation page near the size of a capped CI log. */
108const CONVERSATION_PAGE_CHARS = 32_000;
109const THREAD_COMMENT_PAGES = 4;
110/** Diff pages searched for review comment lines; a PR past this is too big to review by line. */
111const REVIEW_DIFF_PAGES = 10;
112​
113function conversationPage(
114 activity: PullRequestActivity,
115 start: { readonly threads: number; readonly comments: number },
116 includeResolved: boolean,
117) {
118 // Offsets index the unfiltered lists, whose order resolving a thread does not change.
119 const { reviewThreads, comments } = activity;
120 const pageThreads: Array<PullRequestReviewThread> = [];
121 const pageComments: Array<PullRequestActivity["comments"][number]> = [];
122 let size = 0;
123 let thread = Math.min(start.threads, reviewThreads.length);
124 let comment = Math.min(start.comments, comments.length);
125 const fits = (item: unknown) => {
126 const next = size + JSON.stringify(item).length;
127 if (next > CONVERSATION_PAGE_CHARS && pageThreads.length + pageComments.length > 0) {
128 return false;
129 }
130 size = next;
131 return true;
132 };
133 // Review threads come first: they hold the feedback an agent acts on.
134 while (thread < reviewThreads.length) {
135 const next = reviewThreads[thread]!;
136 if (includeResolved || !next.isResolved) {
137 if (!fits(next)) break;
138 pageThreads.push(next);
139 }
140 thread += 1;
141 }
142 if (thread === reviewThreads.length) {
143 while (comment < comments.length && fits(comments[comment])) {
144 pageComments.push(comments[comment++]!);
145 }
146 }
147 const done = thread === reviewThreads.length && comment === comments.length;
148 return {
149 threads: pageThreads,
150 comments: pageComments,
151 hiddenResolvedThreads: includeResolved
152 ? 0
153 : reviewThreads.filter((candidate) => candidate.isResolved).length,
154 next: done ? null : { threads: thread, comments: comment, includeResolved },
155 };
157​
158function entryOf(
159 link: ThreadPullRequestLink,
160 chains: ReturnType<typeof resolveThreadPullRequestChains>,
161): ThreadPullRequestEntry {
162 const key = threadPullRequestKeyOf(link);
163 let stack: ThreadPullRequestEntry["stack"] = null;
164 for (const chain of chains) {
165 if (chain.layers.length < 2) continue;
166 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
167 if (index !== -1) {
168 stack = { kind: chain.kind, position: chain.depths[index]! + 1, size: chain.layers.length };
169 break;
170 }
171 }
172 return {
173 host: normalizeThreadPullRequestKey(link).host,
174 repository: link.repository,
175 number: link.number,
176 url: link.url,
177 source: link.source,
178 watching: link.watch !== undefined,
179 state: link.snapshot?.state ?? null,
180 title: link.snapshot?.title ?? null,
181 headBranch: link.snapshot?.headBranch ?? null,
182 baseBranch: link.snapshot?.baseBranch ?? null,
183 isDraft: link.snapshot?.isDraft ?? null,
184 stack,
185 };
187​
188const PULL_REQUEST_LIST_PAGE_SIZE = 50;
189​
190// A total order that survives unlinking: the cursor names a position, not an index, so removing
191// PRs already returned cannot skip later ones. PRs linked in one call share `linkedAt`.
192function pullRequestListPosition(link: ThreadPullRequestLink): string {
193 return [link.linkedAt, link.host, link.repository, String(link.number).padStart(10, "0")].join(
194 " ",
195 );
197​
198export function listThreadPullRequests(
199 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
200 cursor?: string,
201 states?: ReadonlyArray<PullRequestState>,
202): ListThreadPullRequestsResult {
203 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
204 const after = visibleThreadPullRequests(thread.pullRequests ?? [])
205 .filter((link) => states === undefined || states.includes(link.snapshot?.state ?? "open"))
206 .map((link) => ({ link, position: pullRequestListPosition(link) }))
207 .filter(({ position }) => cursor === undefined || position > cursor)
208 .toSorted((left, right) => (left.position < right.position ? -1 : 1));
209 const page = after.slice(0, PULL_REQUEST_LIST_PAGE_SIZE);
210 const pageKeys = new Set(page.map(({ link }) => threadPullRequestKeyOf(link)));
211 return {
212 pullRequests: page.map(({ link }) => entryOf(link, chains)),
213 // Stacks with a pull request on this page, whole.
214 chains: chains
215 .filter((chain) => chain.layers.some((layer) => pageKeys.has(threadPullRequestKeyOf(layer))))
216 .map((chain) => ({
217 kind: chain.kind,
218 numbers: chain.layers.map((layer) => layer.number),
219 })),
220 nextCursor: after.length > page.length ? page.at(-1)!.position : null,
221 };
223​
224function projectForPullRequest(
225 projects: ReadonlyArray<OrchestrationProjectShell>,
226 target: { readonly host: string; readonly repository: string },
227 preferred: OrchestrationProjectShell | undefined,
228): OrchestrationProjectShell | undefined {
229 // Match the guide service's host-level repository key, including Azure DevOps org/project/_git/repo.
230 const matches = (project: OrchestrationProjectShell) => {
231 const own = pullRequestSyncKey(
232 { projectId: project.id, host: target.host, repository: target.repository, number: 1 },
233 project.repositoryIdentity ?? undefined,
234 );
235 const projectKey =
236 project.repositoryIdentity == null
237 ? null
238 : pullRequestSyncKey(
239 {
240 projectId: project.id,
241 repository:
242 sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? "",
243 number: 1,
244 },
245 project.repositoryIdentity,
246 );
247 return (
248 own !== null &&
249 projectKey !== null &&
250 own.host === projectKey.host &&
251 own.repository === projectKey.repository
252 );
253 };
254 if (preferred !== undefined && matches(preferred)) return preferred;
255 return projects.find(matches);
257​
258const make = Effect.gen(function* () {
259 const engine = yield* Orchestrator.OrchestratorV2;
260 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
261 const watches = yield* PullRequestWatchService.PullRequestWatchService;
262 const pullRequests = yield* PullRequestService.PullRequestService;
263 const git = yield* GitManager.GitManager;
264​
265 const projects = yield* ProjectService.ProjectService;
266 const random = yield* SecureRandom.SecureRandom;
267​
268 const commandId = (tag: string, threadId: ThreadId) =>
269 random.uuidV4().pipe(
270 Effect.orDie,
271 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
272 );
273​
274 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
275 Failure:
276 | typeof PullRequestLinkFailedError
277 | typeof PullRequestUnlinkFailedError
278 | typeof PullRequestListFailedError
279 | typeof PullRequestForgeError,
280 requested: ThreadId | undefined,
281 ) {
282 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
283 const threadId = requested ?? scope.thread?.threadId;
284 if (threadId === undefined) {
285 return yield* new PullRequestThreadRequiredError();
286 }
287 const thread = yield* engine.getThreadShell(threadId).pipe(
288 Effect.map(Option.fromNullishOr),
289 Effect.mapError((cause) => new Failure({ cause })),
290 );
291 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
292 return yield* threadNotFound(engine, scope, threadId, `Thread ${threadId} was not found.`);
293 }
294 return thread.value;
295 });
296​
297 const projectOf = (
298 thread: OrchestrationV2ThreadShell,
299 Failure:
300 | typeof PullRequestLinkFailedError
301 | typeof PullRequestUnlinkFailedError
302 | typeof PullRequestForgeError,
303 ) =>
304 projects.getShell(thread.projectId).pipe(
305 Effect.map(Option.getOrUndefined),
306 Effect.mapError((cause) => new Failure({ cause })),
307 );
308​
309 const dispatchFailure =
310 (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) =>
311 <E>(
312 cause: Cause.Cause<E>,
313 ): Effect.Effect<never, PullRequestLinkFailedError | PullRequestUnlinkFailedError> =>
314 Cause.hasInterruptsOnly(cause)
315 ? Effect.failCause(cause as Cause.Cause<never>)
316 : Effect.fail(new Failure({ cause }));
317​
318 // The domain service owns the registration span.
319 const setWatching = Effect.fnUntraced(function* (
320 input: PullRequestTargetInput & { readonly until?: PullRequestWatchUntil | undefined },
321 watching: boolean,
322 ) {
323 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
324 const threadId = input.threadId ?? scope.thread?.threadId;
325 if (threadId === undefined) return yield* new PullRequestThreadRequiredError();
326 return yield* watches
327 .setWatching({ threadId, target: input, watching, until: input.until })
328 .pipe(
329 Effect.catchTags({
330 PullRequestWatchThreadNotFoundError: (error) =>
331 threadNotFound(engine, scope, error.threadId, error.message),
332 }),
333 );
334 });
335​
336 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
337 targets: ReadonlyArray<Omit<PullRequestTargetInput, "threadId">>,
338 ) {
339 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
340 const callerThread =
341 scope.thread === undefined
342 ? undefined
343 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
344 Effect.orElseSucceed(() => null),
345 Effect.map((shell) => shell ?? undefined),
346 );
347 const known = yield* projects
348 .listShells()
349 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
350 const callerProject = known.find((project) => project.id === callerThread?.projectId);
351 // A pull request named by host and repository builds its URL through the project that holds
352 // it, which need not be the caller's.
353 const urlProject = (input: PullRequestTargetInput) =>
354 input.url === undefined && input.host !== undefined && input.repository !== undefined
355 ? (projectForPullRequest(
356 known,
357 { host: input.host, repository: input.repository },
358 callerProject,
359 ) ?? callerProject)
360 : callerProject;
361 return yield* Effect.forEach(targets, (input) =>
362 resolveTarget(input, urlProject(input)).pipe(
363 Effect.map((target) => ({
364 input,
365 target,
366 project: projectForPullRequest(known, target, callerProject),
367 callerProject,
368 failure: null,
369 })),
370 Effect.catch((error) =>
371 Effect.succeed({
372 input,
373 target: null,
374 project: undefined,
375 callerProject,
376 failure: error.message,
377 }),
378 ),
379 ),
380 );
381 });
382​
383 const guideReference = (
384 project: OrchestrationProjectShell,
385 target: { readonly host: string; readonly repository: string; readonly number: number },
386 ) => ({
387 projectId: project.id,
388 host: target.host,
389 repository: target.repository,
390 number: target.number,
391 });
392​
393 const guideFailureDetail = (error: { readonly message: string }) =>
394 "detail" in error && typeof error.detail === "string" ? error.detail : error.message;
395​
396 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
397 handle: (params: P) => Effect.Effect<A, E, R>,
398 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
399​
400 const forgeFailure = (error: { readonly message: string }) =>
401 new PullRequestForgeError({ detail: error.message, cause: error });
402​
403 // Layers below the target are pinned to the heads read here; the host refuses if any moved.
404 const stackMergeScope = Effect.fnUntraced(function* (
405 ref: PullRequestRef,
406 input: { readonly expectedHeadSha: string; readonly auto?: boolean | undefined },
407 ) {
408 if (input.auto === true)
409 return yield* new PullRequestForgeError({ detail: "A stack merge cannot wait with auto." });
410 const stack = yield* pullRequests
411 .stack(ref, { bypassCache: true })
412 .pipe(Effect.mapError(forgeFailure));
413 const end = stack?.layers.findIndex((layer) => layer.number === ref.number) ?? -1;
414 if (stack === null || end === -1)
415 return yield* new PullRequestForgeError({
416 detail: `PR #${ref.number} is not in a stack this host can merge. Merge it without stack.`,
417 });
418 const expectedStackHeads: Array<{ readonly number: number; readonly headSha: string }> = [];
419 for (const layer of stack.layers.slice(0, end + 1)) {
420 if (layer.state === "merged") continue;
421 const headSha = layer.number === ref.number ? input.expectedHeadSha : layer.headSha;
422 if (headSha === undefined)
423 return yield* new PullRequestForgeError({
424 detail: `The host did not report PR #${layer.number}'s head, so the stack cannot be pinned. Try again.`,
425 });
426 expectedStackHeads.push({ number: layer.number, headSha });
427 }
428 return { stackNumber: stack.number, expectedStackHeads };
429 });
430​
431 /** A login or org/team, matched to the host's own reviewer id. */
432 const reviewerNamed = (ref: PullRequestRef, name: string) =>
433 pullRequests.reviewerCandidates({ ...ref, query: name }).pipe(
434 Effect.mapError(forgeFailure),
435 Effect.flatMap(({ candidates }) => {
436 const wanted = name.toLowerCase();
437 const match = candidates.find(
438 (candidate) =>
439 candidate.login.toLowerCase() === wanted || candidate.id.toLowerCase() === wanted,
440 );
441 return match === undefined
442 ? Effect.fail(
443 new PullRequestForgeError({
444 detail: `No reviewer named ${name} can be requested on this PR.`,
445 }),
446 )
447 : Effect.succeed({ id: match.id, kind: match.kind });
448 }),
449 );
450​
451 /** Line comments placed by the PR's diff, which says whether each line was added, removed, or kept. */
452 const reviewComments = Effect.fn("PullRequestsToolkit.reviewComments")(function* (
453 ref: PullRequestRef,
454 comments: ReadonlyArray<ReviewLineComment>,
455 ) {
456 const placed = new Map<ReviewLineComment, PullRequestReviewCommentDraft>();
457 const unplaced = () => comments.filter((comment) => !placed.has(comment));
458 let cursor: string | undefined;
459 for (let page = 0; page < REVIEW_DIFF_PAGES && unplaced().length > 0; page += 1) {
460 const diff = yield* pullRequests
461 .diff({ ...ref, ...(cursor === undefined ? {} : { cursor }) })
462 .pipe(Effect.mapError(forgeFailure));
463 for (const comment of unplaced()) {
464 const side = comment.side ?? "new";
465 const position = reviewPositionInPatch(diff.patch, comment.path, comment.line, side);
466 const start =
467 comment.startLine === undefined
468 ? undefined
469 : reviewPositionInPatch(diff.patch, comment.path, comment.startLine, side);
470 if (position === null || start === null) continue;
471 placed.set(comment, {
472 path: comment.path,
473 position,
474 ...(start === undefined ? {} : { startPosition: start }),
475 body: comment.body,
476 });
477 }
478 if (diff.nextCursor === null) break;
479 cursor = diff.nextCursor;
480 }
481 const missing = unplaced()[0];
482 if (missing !== undefined) {
483 return yield* new PullRequestForgeError({
484 detail: `${missing.path} line ${missing.startLine ?? missing.line} (${missing.side ?? "new"} side) is not in this PR's diff. Comment on a changed line or one shown around it.`,
485 });
486 }
487 return comments.map((comment) => placed.get(comment)!);
488 });
489​
490 /** The thread's checkout, its project, and the PR the input names (default: the branch's). */
491 const locate = Effect.fn("PullRequestsToolkit.locate")(function* (input: ThreadPullRequestInput) {
492 const thread = yield* requireThread(PullRequestForgeError, undefined);
493 const project = yield* projectOf(thread, PullRequestForgeError);
494 if (project === undefined) {
495 return yield* new PullRequestProjectNotFoundError({ repository: input.repository ?? "" });
496 }
497 // Status sync sets branchPullRequest later, so a PR this thread just opened counts too,
498 // unless it is another branch's.
499 const opened =
500 thread.branchPullRequest === null || thread.branchPullRequest === undefined
501 ? threadPullRequestsOf(thread).findLast(
502 (link) =>
503 link.source === "created" &&
504 (link.snapshot === null || link.snapshot.headBranch === thread.branch),
505 )
506 : undefined;
507 const branchPullRequest = thread.branchPullRequest ?? opened ?? null;
508 const branchRepository =
509 project.repositoryIdentity == null
510 ? undefined
511 : (sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? undefined);
512 const named =
513 input.number !== undefined
514 ? { number: input.number, repository: input.repository ?? branchRepository }
515 : branchPullRequest === null
516 ? null
517 : { number: branchPullRequest.number, repository: branchPullRequest.repository };
518 if (named === null) return yield* new PullRequestBranchHasNoneError();
519 const target = yield* resolveTarget(named, project);
520 const ref: PullRequestRef = {
521 projectId: project.id,
522 host: target.host,
523 repository: target.repository,
524 number: target.number,
525 };
526 if (input.number === undefined && opened !== undefined && opened.snapshot === null) {
527 // Not synced yet, so only the host knows which branch it was opened from.
528 const summary = yield* pullRequests.summary(ref).pipe(Effect.mapError(forgeFailure));
529 if (summary.headBranch !== thread.branch) return yield* new PullRequestBranchHasNoneError();
530 }
531 return { thread, project, target, ref };
532 });
533​
534 const identityOf = (target: ResolvedTarget) => ({
535 host: target.host,
536 repository: target.repository,
537 number: target.number,
538 url: target.url,
539 });
540​
541 /** The thread's comments past its first page, when the host pages them. */
542 const restOfThread = Effect.fn("PullRequestsToolkit.restOfThread")(function* (
543 ref: PullRequestRef,
544 thread: PullRequestReviewThread,
545 ) {
546 const comments: Array<PullRequestReviewThread["comments"][number]> = [];
547 let cursor = thread.nextCommentsCursor;
548 for (let page = 0; cursor !== undefined && page < THREAD_COMMENT_PAGES; page += 1) {
549 const read = yield* pullRequests
550 .threadComments({ ...ref, threadId: thread.id, cursor })
551 .pipe(Effect.option);
552 if (Option.isNone(read)) break;
553 comments.push(...read.value.comments);
554 cursor = read.value.nextCursor ?? undefined;
555 }
556 return { comments, moreComments: cursor !== undefined };
557 });
558​
559 const readSections = Effect.fn("PullRequestsToolkit.readSections")(function* (
560 ref: PullRequestRef,
561 sections: ReadonlyArray<PullRequestReadSection>,
562 includeResolved: boolean,
563 cursor: ReadCursor | undefined,
564 ) {
565 const wants = (section: PullRequestReadSection) => sections.includes(section);
566 const diffCursor = cursor !== undefined && "diff" in cursor ? cursor.diff : undefined;
567 const [detail, activity, diff] = yield* Effect.all(
568 [
569 // Agents pin merges to this headSha, so it must not come from a stale snapshot.
570 wants("summary") || wants("checks")
571 ? pullRequests.detail({ ...ref, allowStale: false }).pipe(Effect.asSome)
572 : Effect.succeedNone,
573 wants("conversation") ? pullRequests.activity(ref).pipe(Effect.asSome) : Effect.succeedNone,
574 wants("diff")
575 ? pullRequests
576 .diff({ ...ref, ...(diffCursor === undefined ? {} : { cursor: diffCursor }) })
577 .pipe(Effect.asSome)
578 : Effect.succeedNone,
579 ],
580 { concurrency: "unbounded" },
581 ).pipe(Effect.mapError(forgeFailure));
582 const page = Option.map(activity, (value) =>
583 conversationPage(
584 value,
585 cursor !== undefined && "threads" in cursor ? cursor : { threads: 0, comments: 0 },
586 includeResolved,
587 ),
588 );
589 const threadRests = Option.isSome(page)
590 ? yield* Effect.forEach(page.value.threads, (thread) => restOfThread(ref, thread), {
591 concurrency: 4,
592 })
593 : [];
594 const result: Omit<ReadPullRequestResult, "host" | "repository" | "number" | "url"> = {
595 ...(Option.isSome(detail) && wants("summary")
596 ? {
597 summary: {
598 title: detail.value.title,
599 body: detail.value.body,
600 state: detail.value.state,
601 isDraft: detail.value.isDraft,
602 author: detail.value.author?.login ?? null,
603 headBranch: detail.value.headBranch,
604 baseBranch: detail.value.baseBranch,
605 headSha: detail.value.headSha ?? null,
606 mergeability: detail.value.mergeability,
607 behindBy: detail.value.behindBy ?? null,
608 autoMergeEnabled: detail.value.autoMergeEnabled ?? null,
609 additions: detail.value.additions,
610 deletions: detail.value.deletions,
611 changedFiles: detail.value.changedFiles,
612 labels: detail.value.labels.map((label) => label.name),
613 reviewers: detail.value.reviewers.map((reviewer) => reviewer.login),
614 },
615 }
616 : {}),
617 ...(Option.isSome(detail) && wants("checks") ? { checks: detail.value.checks } : {}),
618 ...(Option.isSome(activity) && Option.isSome(page)
619 ? {
620 conversation: {
621 comments: page.value.comments.map((comment) => ({
622 id: comment.id,
623 kind: comment.kind,
624 author: comment.author?.login ?? null,
625 body: comment.body,
626 createdAt: comment.createdAt,
627 path: comment.path,
628 reviewState: comment.reviewState,
629 })),
630 reviewThreads: page.value.threads.map((thread, index) => ({
631 id: thread.id,
632 path: thread.path,
633 line: thread.line,
634 isResolved: thread.isResolved,
635 isOutdated: thread.isOutdated,
636 comments: [...thread.comments, ...threadRests[index]!.comments].map((comment) => ({
637 author: comment.author?.login ?? null,
638 body: comment.body,
639 createdAt: comment.createdAt,
640 })),
641 moreComments: threadRests[index]!.moreComments,
642 })),
643 hiddenResolvedThreads: page.value.hiddenResolvedThreads,
644 truncated:
645 activity.value.commentsTruncated || activity.value.reviewThreadsTruncated === true,
646 nextCursor: page.value.next === null ? null : readCursors.encode(page.value.next),
647 },
648 }
649 : {}),
650 ...(Option.isSome(diff)
651 ? {
652 diff: {
653 patch: diff.value.patch,
654 truncated: diff.value.truncated,
655 nextCursor:
656 diff.value.nextCursor === null
657 ? null
658 : readCursors.encode({ diff: diff.value.nextCursor }),
659 },
660 }
661 : {}),
662 };
663 return result;
664 });
665​
666 const linkToThread = Effect.fn("PullRequestsToolkit.linkToThread")(function* (
667 thread: OrchestrationV2ThreadShell,
668 target: ResolvedTarget,
669 ) {
670 if (
671 threadPullRequestsOf(thread).some(
672 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
673 )
674 ) {
675 return;
676 }
677 yield* engine
678 .dispatch({
679 type: "thread.pull-request.link",
680 commandId: yield* commandId("mcp-pr-create", thread.id),
681 threadId: thread.id,
682 host: target.host,
683 repository: target.repository,
684 number: target.number,
685 url: target.url,
686 source: "created",
687 })
688 .pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)));
689 });
690​
691 return {
692 link_pull_request: writesThread((input) =>
693 Effect.gen(function* () {
694 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
695 const next =
696 thread.lineage.relationshipToParent === "subagent"
697 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
698 : {};
699 const project = yield* projectOf(thread, PullRequestLinkFailedError);
700 const target = yield* resolveTarget(input, project);
701 const existing = threadPullRequestsOf(thread).find((link) =>
702 threadPullRequestKeysEqual(link, target),
703 );
704 if (existing && existing.source !== "stack-dismissed")
705 return { ...target, alreadyLinked: true, ...next };
706 const alreadyLinked = yield* engine
707 .dispatch({
708 type: "thread.pull-request.link",
709 commandId: yield* commandId("mcp-pr-link", thread.id),
710 threadId: thread.id,
711 host: target.host,
712 repository: target.repository,
713 number: target.number,
714 url: target.url,
715 source: "agent",
716 })
717 .pipe(
718 Effect.as(false),
719​
720 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
721 );
722 return { ...target, alreadyLinked, ...next };
723 }),
724 ),
725 link_pull_requests: writesThread((input) =>
726 Effect.gen(function* () {
727 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
728 const targets: Array<ResolvedTarget> = [];
729 const invalidUrls: Array<string> = [];
730 for (const url of input.urls) {
731 const target = yield* resolveTarget({ url }, undefined).pipe(Effect.option);
732 if (Option.isNone(target)) invalidUrls.push(url);
733 else if (!targets.some((seen) => threadPullRequestKeysEqual(seen, target.value)))
734 targets.push(target.value);
735 }
736 const links = threadPullRequestsOf(thread);
737 const isLinked = (target: ResolvedTarget) =>
738 links.some(
739 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
740 );
741 const fresh = targets.filter((target) => !isLinked(target));
742 const alreadyLinked = targets.filter(isLinked);
743 yield* Effect.forEach(fresh, (target) =>
744 Effect.gen(function* () {
745 yield* engine.dispatch({
746 type: "thread.pull-request.link",
747 commandId: yield* commandId("mcp-pr-link", thread.id),
748 threadId: thread.id,
749 host: target.host,
750 repository: target.repository,
751 number: target.number,
752 url: target.url,
753 source: "agent",
754 });
755 }).pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError))),
756 );
757 const byRepository = (prs: ReadonlyArray<ResolvedTarget>) =>
758 [...Map.groupBy(prs, (pr) => `${pr.host}/${pr.repository}`).values()].map((group) => ({
759 host: group[0]!.host,
760 repository: group[0]!.repository,
761 numbers: group.map((pr) => pr.number),
762 }));
763 return {
764 linked: byRepository(fresh),
765 alreadyLinked: byRepository(alreadyLinked),
766 linkedCount: targets.length,
767 ...(invalidUrls.length > 0 ? { invalidUrls } : {}),
768 ...(thread.lineage.relationshipToParent === "subagent"
769 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
770 : {}),
771 };
772 }),
773 ),
774 unlink_pull_request: writesThread((input) =>
775 Effect.gen(function* () {
776 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
777 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
778 const target = yield* resolveTarget(input, project);
779 if (
780 !threadPullRequestsOf(thread).some(
781 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
782 )
783 )
784 return {
785 host: target.host,
786 repository: target.repository,
787 number: target.number,
788 wasLinked: false,
789 };
790 const wasLinked = yield* engine
791 .dispatch({
792 type: "thread.pull-request.unlink",
793 commandId: yield* commandId("mcp-pr-unlink", thread.id),
794 threadId: thread.id,
795 host: target.host,
796 repository: target.repository,
797 number: target.number,
798 })
799 .pipe(
800 Effect.as(true),
801​
802 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
803 );
804 return {
805 host: target.host,
806 repository: target.repository,
807 number: target.number,
808 wasLinked,
809 };
810 }),
811 ),
812 unlink_pull_requests: writesThread((input) =>
813 Effect.gen(function* () {
814 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
815 const visible = visibleThreadPullRequests(threadPullRequestsOf(thread));
816 const matching = visible.flatMap((link) => {
817 const state = link.snapshot?.state;
818 return state !== undefined && input.states.includes(state)
819 ? [{ ...normalizeThreadPullRequestKey(link), state }]
820 : [];
821 });
822 yield* Effect.forEach(matching, ({ host, repository, number }) =>
823 Effect.gen(function* () {
824 yield* engine.dispatch({
825 type: "thread.pull-request.unlink",
826 commandId: yield* commandId("mcp-pr-unlink", thread.id),
827 threadId: thread.id,
828 host,
829 repository,
830 number,
831 });
832 }).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))),
833 );
834 // Numbers grouped by repository and state keep a large batch's result small.
835 const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`);
836 return {
837 unlinked: [...groups.values()].map((prs) => ({
838 host: prs[0]!.host,
839 repository: prs[0]!.repository,
840 state: prs[0]!.state,
841 numbers: prs.map((pr) => pr.number),
842 })),
843 unlinkedCount: matching.length,
844 remaining: visible.length - matching.length,
845 };
846 }),
847 ),
848 list_thread_pull_requests: McpToolAccess.reads((input) =>
849 requireThread(PullRequestListFailedError, input.threadId).pipe(
850 Effect.map((thread) => listThreadPullRequests(thread, input.cursor, input.states)),
851 ),
852 ),
853 watch_pull_request: writesThread((input) => setWatching(input, true)),
854 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
855 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
856 Effect.gen(function* () {
857 const located = yield* locateAll(input.pullRequests);
858 const guides = yield* Effect.forEach(
859 located,
860 (entry) =>
861 Effect.gen(function* () {
862 if (entry.target === null) {
863 return {
864 host: entry.input.host ?? "",
865 repository: entry.input.repository ?? "",
866 number: entry.input.number ?? 0,
867 url: entry.input.url ?? "",
868 outcome: "failed" as const,
869 detail: entry.failure,
870 };
871 }
872 const identity = {
873 host: entry.target.host,
874 repository: entry.target.repository,
875 number: entry.target.number,
876 url: entry.target.url,
877 };
878 if (entry.project === undefined) {
879 return {
880 ...identity,
881 outcome: "failed" as const,
882 detail: new PullRequestProjectNotFoundError({
883 repository: entry.target.repository,
884 }).message,
885 };
886 }
887 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
888 Effect.map((result) => ({
889 ...identity,
890 outcome: result.started ? ("started" as const) : ("running" as const),
891 detail: null,
892 })),
893 Effect.catch((error) =>
894 Effect.succeed({
895 ...identity,
896 outcome: "failed" as const,
897 detail: guideFailureDetail(error),
898 }),
899 ),
900 );
901 }),
902 { concurrency: 4 },
903 );
904 return { guides };
905 }),
906 ),
907 read_pull_request_guide: McpToolAccess.reads((input) =>
908 Effect.gen(function* () {
909 const [entry] = yield* locateAll([input]);
910 if (entry !== undefined && entry.target === null) {
911 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
912 }
913 // Hosts readable without a checkout (GitHub, Bitbucket, Forgejo) are read through the
914 // caller's project; PullRequestService decides whether the host allows that.
915 const project = entry?.project ?? entry?.callerProject;
916 if (entry === undefined || entry.target === null || project === undefined) {
917 return yield* new PullRequestProjectNotFoundError({
918 repository: entry?.target.repository ?? input.repository ?? "",
919 });
920 }
921 const target = entry.target;
922 const result = yield* reviewGuides.get(guideReference(project, target)).pipe(
923 Effect.mapError((error) =>
924 entry.project === undefined &&
925 error._tag === "PullRequestUnavailableError" &&
926 (error.reason === "provider-unsupported" ||
927 error.reason === "repository-without-project")
928 ? new PullRequestProjectNotFoundError({ repository: target.repository })
929 : new PullRequestGuideFailedError({
930 detail: guideFailureDetail(error),
931 cause: error,
932 }),
933 ),
934 );
935 return {
936 host: entry.target.host,
937 repository: entry.target.repository,
938 number: entry.target.number,
939 url: entry.target.url,
940 guide: result.guide,
941 run: result.run,
942 currentHeadSha: result.currentHeadSha,
943 stale:
944 result.guide !== null &&
945 result.currentHeadSha !== null &&
946 result.guide.headSha !== result.currentHeadSha,
947 };
948 }),
949 ),
950 pull_request_read: McpToolAccess.reads((input) =>
951 Effect.gen(function* () {
952 const cursor =
953 input.cursor === undefined ? undefined : yield* readCursors.decode(input.cursor);
954 const { target, ref } = yield* locate(input);
955 // A cursor continues the one section it came from, with that read's options.
956 const sections: ReadonlyArray<PullRequestReadSection> =
957 cursor === undefined
958 ? (input.sections ?? ["summary", "checks"])
959 : "diff" in cursor
960 ? ["diff"]
961 : ["conversation"];
962 const includeResolved =
963 cursor !== undefined && "includeResolved" in cursor
964 ? cursor.includeResolved
965 : input.includeResolved === true;
966 return {
967 ...identityOf(target),
968 ...(yield* readSections(ref, sections, includeResolved, cursor)),
969 };
970 }),
971 ),
972 pull_request_list: McpToolAccess.reads((input) =>
973 Effect.gen(function* () {
974 const thread = yield* requireThread(PullRequestForgeError, undefined);
975 const listed = yield* pullRequests
976 .list({
977 projectId: thread.projectId,
978 state: input.state ?? "open",
979 involvement: input.involvement ?? "all",
980 limit: input.limit ?? 30,
981 ...(input.query === undefined ? {} : { query: input.query }),
982 ...(input.cursor === undefined
983 ? {}
984 : { cursors: yield* listCursors.decode(input.cursor) }),
985 })
986 .pipe(Effect.mapError(forgeFailure));
987 const failure = listed.errors[0];
988 if (listed.entries.length === 0 && failure !== undefined) {
989 return yield* new PullRequestForgeError({ detail: failure.message });
990 }
991 return {
992 pullRequests: listed.entries.map((entry) => ({
993 number: entry.number,
994 title: entry.title,
995 url: entry.url,
996 author: entry.author?.login ?? null,
997 headBranch: entry.headBranch,
998 baseBranch: entry.baseBranch,
999 state: entry.state,
1000 isDraft: entry.isDraft,
1001 reviewDecision: entry.reviewDecision ?? null,
1002 checksState: entry.checksState ?? null,
1003 updatedAt: entry.updatedAt,
1004 })),
1005 truncated: listed.truncated,
1006 nextCursor:
1007 Object.keys(listed.nextCursors).length === 0
1008 ? null
1009 : listCursors.encode(listed.nextCursors),
1010 };
1011 }),
1012 ),
1013 pull_request_create: McpToolAccess.writesWithCapability((input) =>
1014 Effect.gen(function* () {
1015 const thread = yield* requireThread(PullRequestForgeError, undefined);
1016 const project = yield* projectOf(thread, PullRequestForgeError);
1017 if (project === undefined) {
1018 return yield* new PullRequestProjectNotFoundError({ repository: "" });
1020 const created = yield* git
1021 .createPullRequest({
1022 cwd: thread.worktreePath ?? project.workspaceRoot,
1023 projectId: project.id,
1024 title: input.title,
1025 body: input.body,
1026 baseBranch: input.base,
1027 draft: input.draft,
1028 })
1029 .pipe(Effect.mapError(forgeFailure));
1030 if (created.url === undefined) {
1031 return yield* new PullRequestForgeError({
1032 detail:
1033 "The host accepted the PR but does not list it yet. Find it with pull_request_list.",
1034 });
1036 const target = yield* resolveTarget({ url: created.url }, project);
1037 yield* linkToThread(thread, target);
1038 return {
1039 ...identityOf(target),
1040 created: created.status === "created",
1041 ...(thread.lineage.relationshipToParent === "subagent"
1042 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
1043 : {}),
1044 };
1045 }),
1046 ),
1047 pull_request_update: McpToolAccess.writesWithCapability((input) =>
1048 Effect.gen(function* () {
1049 if (
1050 input.title === undefined &&
1051 input.body === undefined &&
1052 input.ready === undefined &&
1053 input.state === undefined &&
1054 input.addLabels === undefined &&
1055 input.removeLabels === undefined &&
1056 input.requestReviewers === undefined
1057 ) {
1058 return yield* new PullRequestNothingToDoError({
1059 detail: "Pass title, body, ready, state, addLabels, removeLabels, or requestReviewers.",
1060 });
1062 const { target, ref } = yield* locate(input);
1063 if (input.title !== undefined || input.body !== undefined) {
1064 yield* pullRequests
1065 .update({
1066 ...ref,
1067 ...(input.title === undefined ? {} : { title: input.title }),
1068 ...(input.body === undefined ? {} : { body: input.body }),
1069 })
1070 .pipe(Effect.mapError(forgeFailure));
1072 for (const [labels, applied] of [
1073 [input.addLabels, true],
1074 [input.removeLabels, false],
1075 ] as const) {
1076 if (labels !== undefined) {
1077 yield* pullRequests
1078 .setLabels({ ...ref, labels, applied })
1079 .pipe(Effect.mapError(forgeFailure));
1082 if (input.requestReviewers !== undefined) {
1083 const reviewers = yield* Effect.forEach(input.requestReviewers, (name) =>
1084 reviewerNamed(ref, name),
1085 );
1086 yield* pullRequests
1087 .requestReviewers({ ...ref, reviewers, requested: true })
1088 .pipe(Effect.mapError(forgeFailure));
1090 if (input.ready !== undefined) {
1091 yield* pullRequests
1092 .runAction({ ...ref, action: input.ready ? "ready" : "draft" })
1093 .pipe(Effect.mapError(forgeFailure));
1095 if (input.state !== undefined) {
1096 yield* pullRequests
1097 .runAction({ ...ref, action: input.state === "closed" ? "close" : "reopen" })
1098 .pipe(Effect.mapError(forgeFailure));
1100 return identityOf(target);
1101 }),
1102 ),
1103 pull_request_respond: McpToolAccess.writesWithCapability((input) =>
1104 Effect.gen(function* () {
1105 if (
1106 input.body === undefined &&
1107 (input.reviewThreadId === undefined || input.resolved === undefined)
1108 ) {
1109 return yield* new PullRequestNothingToDoError({
1110 detail: "Pass body, or reviewThreadId with resolved.",
1111 });
1113 if (input.reviewThreadId === undefined && input.resolved !== undefined) {
1114 return yield* new PullRequestNothingToDoError({
1115 detail: "resolved needs reviewThreadId.",
1116 });
1118 const { target, ref } = yield* locate(input);
1119 const reviewThreadId = input.reviewThreadId;
1120 if (input.body !== undefined) {
1121 yield* (
1122 reviewThreadId === undefined
1123 ? pullRequests.comment({ ...ref, body: input.body })
1124 : pullRequests.replyToThread({ ...ref, threadId: reviewThreadId, body: input.body })
1125 ).pipe(Effect.mapError(forgeFailure));
1127 if (reviewThreadId !== undefined && input.resolved !== undefined) {
1128 yield* pullRequests
1129 .setThreadResolution({ ...ref, threadId: reviewThreadId, resolved: input.resolved })
1130 .pipe(
1131 Effect.mapError((error) =>
1132 input.body === undefined
1133 ? forgeFailure(error)
1134 : new PullRequestForgeError({
1135 // A retry with the body would post the reply twice.
1136 detail: `The reply was posted, but setting resolved failed: ${error.message} Retry without body.`,
1137 cause: error,
1138 }),
1139 ),
1140 );
1142 return {
1143 ...identityOf(target),
1144 replied: input.body !== undefined,
1145 resolved: input.resolved ?? null,
1146 };
1147 }),
1148 ),
1149 pull_request_review: McpToolAccess.writesWithCapability((input) =>
1150 Effect.gen(function* () {
1151 const { target, ref } = yield* locate(input);
1152 const comments = yield* reviewComments(ref, input.comments ?? []);
1153 yield* pullRequests
1154 .submitReview({ ...ref, verdict: input.verdict, body: input.body ?? "", comments })
1155 .pipe(Effect.mapError(forgeFailure));
1156 return identityOf(target);
1157 }),
1158 ),
1159 pull_request_merge: McpToolAccess.writesWithCapability((input) =>
1160 Effect.gen(function* () {
1161 const { target, ref } = yield* locate(input);
1162 const stack = input.stack === true ? yield* stackMergeScope(ref, input) : {};
1163 yield* pullRequests
1164 .runAction({
1165 ...ref,
1166 action: input.auto === true ? "enable-auto-merge" : "merge",
1167 expectedHeadSha: input.expectedHeadSha,
1168 ...(input.method === undefined ? {} : { mergeMethod: input.method }),
1169 ...stack,
1170 })
1171 .pipe(Effect.mapError(forgeFailure));
1172 const after = yield* pullRequests
1173 .summary({ ...ref, allowStale: false })
1174 .pipe(Effect.mapError(forgeFailure));
1175 return { ...identityOf(target), state: after.state };
1176 }),
1177 ),
1178 ci_logs: McpToolAccess.reads((input) =>
1179 Effect.gen(function* () {
1180 const { target, ref } = yield* locate(input);
1181 const checks = yield* pullRequests
1182 .checkLogs({
1183 ...ref,
1184 tailLines: input.tailLines ?? 200,
1185 ...(input.check === undefined ? {} : { check: input.check }),
1186 })
1187 .pipe(Effect.mapError(forgeFailure));
1188 return { ...identityOf(target), checks };
1189 }),
1190 ),
1191 ci_rerun: McpToolAccess.writesWithCapability((input) =>
1192 Effect.gen(function* () {
1193 const { thread, target, ref } = yield* locate(input);
1194 const checks = yield* pullRequests
1195 .rerunChecks({ ...ref, ...(input.check === undefined ? {} : { check: input.check }) })
1196 .pipe(Effect.mapError(forgeFailure));
1197 // Like a push, a rerun makes a watch's finished checks stale, so the thread keeps working
1198 // until a read sees them run. The rerun already happened, so a failed reopen only logs.
1199 if (
1200 checks.some((check) => check.rerun) &&
1201 threadPullRequestsOf(thread).some((link) => link.watch?.checksPending !== undefined)
1202 ) {
1203 yield* engine
1204 .dispatch({
1205 type: "thread.pull-request-watch.checks-reopen",
1206 commandId: yield* commandId("mcp-ci-rerun-checks", thread.id),
1207 threadId: thread.id,
1208 })
1209 .pipe(
1210 Effect.catchCause((cause) =>
1211 Effect.logWarning("reopening a watch's checks after a rerun failed", cause),
1212 ),
1213 );
1215 return { ...identityOf(target), checks };
1216 }),
1217 ),
1218 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
1219});
1220​
1221export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);