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