Open History to see the last commit
1import {
2 CommandId,
3 pullRequestHostOf,
4 type OrchestrationProjectShell,
5 type OrchestrationThreadShell,
6 type SourceControlProviderKind,
7 type ThreadId,
8 type ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
11import {
12 normalizeThreadPullRequestKey,
13 resolveThreadPullRequestChains,
14 threadPullRequestKeyOf,
15 visibleThreadPullRequests,
16} from "@t3tools/shared/threadPullRequests";
17import * as Cause from "effect/Cause";
18import * as Crypto from "effect/Crypto";
19import * as Effect from "effect/Effect";
20import * as Option from "effect/Option";
21
22import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts";
23import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
24import * as McpInvocationContext from "../../McpInvocationContext.ts";
25import {
26 type ListThreadPullRequestsResult,
27 PullRequestLinkFailedError,
28 PullRequestUrlInvalidError,
29 PullRequestTargetIncompleteError,
30 PullRequestHostRequiredError,
31 PullRequestUnlinkFailedError,
32 PullRequestListFailedError,
33 type PullRequestTargetInput,
34 PullRequestThreadNotFoundError,
35 PullRequestsToolkit,
36 type ThreadPullRequestEntry,
37} from "./tools.ts";
38
39interface ResolvedTarget {
40 readonly host: string;
41 readonly repository: string;
42 readonly number: number;
43 readonly url: string;
44}
45
46/** The project's host and provider supply defaults for a repository-and-number input. */
47function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
48 readonly host: string | null;
49 readonly kind: SourceControlProviderKind | null;
50} {
51 const identity = project?.repositoryIdentity;
52 const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;
53 if (!identity || kind === null) return { host: null, kind: null };
54 return {
55 host: pullRequestHostOf(identity, kind),
56 kind,
57 };
58}
59
60/**
61 * Turns whichever shape the agent passed into one host-level identity. A URL
62 * wins outright; otherwise the repository and number are completed with the
63 * thread's project host, which is where an agent working in that checkout
64 * almost always opened the pull request.
65 */
66const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
67 input: PullRequestTargetInput,
68 project: OrchestrationProjectShell | undefined,
69) {
70 if (input.url !== undefined) {
71 const parsed = parseChangeRequestUrl(input.url);
72 if (parsed === null) {
73 return yield* new PullRequestUrlInvalidError({});
74 }
75 return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
76 }
77 if (input.repository === undefined || input.number === undefined) {
78 return yield* new PullRequestTargetIncompleteError({});
79 }
80 const projectHost = projectHostAndProvider(project);
81 const host = (input.host ?? projectHost.host)?.toLowerCase();
82 if (host === undefined) {
83 return yield* new PullRequestHostRequiredError({});
84 }
85 const repository = input.repository.toLowerCase();
86 const url =
87 changeRequestUrlFor(
88 // The project's kind only describes its own host; another host gets no URL guess.
89 host === projectHost.host ? projectHost.kind : null,
90 host,
91 repository,
92 input.number,
93 project?.repositoryIdentity?.locator.remoteUrl,
94 ) ?? `https://${host}/${repository}/pull/${input.number}`;
95 return {
96 ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
97 url,
98 } satisfies ResolvedTarget;
99});
100
101function entryOf(
102 link: ThreadPullRequestLink,
103 chains: ReturnType<typeof resolveThreadPullRequestChains>,
104): ThreadPullRequestEntry {
105 const key = threadPullRequestKeyOf(link);
106 let stack: ThreadPullRequestEntry["stack"] = null;
107 for (const chain of chains) {
108 if (chain.layers.length < 2) continue;
109 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
110 if (index !== -1) {
111 stack = { kind: chain.kind, position: index + 1, size: chain.layers.length };
112 break;
113 }
114 }
115 return {
116 host: normalizeThreadPullRequestKey(link).host,
117 repository: link.repository,
118 number: link.number,
119 url: link.url,
120 source: link.source,
121 state: link.snapshot?.state ?? null,
122 title: link.snapshot?.title ?? null,
123 headBranch: link.snapshot?.headBranch ?? null,
124 baseBranch: link.snapshot?.baseBranch ?? null,
125 isDraft: link.snapshot?.isDraft ?? null,
126 stack,
127 };
128}
129
130/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
131export function listThreadPullRequests(
132 thread: Pick<OrchestrationThreadShell, "pullRequests">,
133): ListThreadPullRequestsResult {
134 const chains = resolveThreadPullRequestChains(thread.pullRequests);
135 return {
136 pullRequests: visibleThreadPullRequests(thread.pullRequests).map((link) =>
137 entryOf(link, chains),
138 ),
139 chains: chains.map((chain) => ({
140 kind: chain.kind,
141 numbers: chain.layers.map((layer) => layer.number),
142 })),
143 };
144}
145
146const make = Effect.gen(function* () {
147 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
148 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
149 const crypto = yield* Crypto.Crypto;
150
151 const commandId = (tag: string, threadId: ThreadId) =>
152 crypto.randomUUIDv4.pipe(
153 Effect.orDie,
154 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
155 );
156
157 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
158 Failure:
159 | typeof PullRequestLinkFailedError
160 | typeof PullRequestUnlinkFailedError
161 | typeof PullRequestListFailedError,
162 ) {
163 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
164 const thread = yield* snapshots
165 .getThreadShellById(scope.threadId)
166 .pipe(Effect.mapError((cause) => new Failure({ cause })));
167 if (Option.isNone(thread)) {
168 return yield* new PullRequestThreadNotFoundError({ threadId: scope.threadId });
169 }
170 return thread.value;
171 });
172
173 const projectOf = (
174 thread: OrchestrationThreadShell,
175 Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError,
176 ) =>
177 snapshots.getProjectShellById(thread.projectId).pipe(
178 Effect.map(Option.getOrUndefined),
179 Effect.mapError((cause) => new Failure({ cause })),
180 );
181
182 const dispatchFailure =
183 (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) =>
184 <E>(
185 cause: Cause.Cause<E>,
186 ): Effect.Effect<never, PullRequestLinkFailedError | PullRequestUnlinkFailedError> =>
187 Cause.hasInterruptsOnly(cause)
188 ? Effect.failCause(cause as Cause.Cause<never>)
189 : Effect.fail(new Failure({ cause }));
190
191 return PullRequestsToolkit.of({
192 link_pull_request: (input) =>
193 Effect.gen(function* () {
194 const thread = yield* requireThread(PullRequestLinkFailedError);
195 const project = yield* projectOf(thread, PullRequestLinkFailedError);
196 const target = yield* resolveTarget(input, project);
197 const alreadyLinked = yield* engine
198 .dispatch({
199 type: "thread.pull-request.link",
200 commandId: yield* commandId("mcp-pr-link", thread.id),
201 threadId: thread.id,
202 host: target.host,
203 repository: target.repository,
204 number: target.number,
205 url: target.url,
206 source: "agent",
207 })
208 .pipe(
209 Effect.as(false),
210 // The decider rejects a second link of the same PR; for the agent that is
211 // the outcome it asked for, not an error.
212 Effect.catchTags({ OrchestrationCommandInvariantError: () => Effect.succeed(true) }),
213 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
214 );
215 return { ...target, alreadyLinked };
216 }),
217 unlink_pull_request: (input) =>
218 Effect.gen(function* () {
219 const thread = yield* requireThread(PullRequestUnlinkFailedError);
220 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
221 const target = yield* resolveTarget(input, project);
222 const wasLinked = yield* engine
223 .dispatch({
224 type: "thread.pull-request.unlink",
225 commandId: yield* commandId("mcp-pr-unlink", thread.id),
226 threadId: thread.id,
227 host: target.host,
228 repository: target.repository,
229 number: target.number,
230 })
231 .pipe(
232 Effect.as(true),
233 Effect.catchTags({ OrchestrationCommandInvariantError: () => Effect.succeed(false) }),
234 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
235 );
236 return {
237 host: target.host,
238 repository: target.repository,
239 number: target.number,
240 wasLinked,
241 };
242 }),
243 list_thread_pull_requests: () =>
244 requireThread(PullRequestListFailedError).pipe(Effect.map(listThreadPullRequests)),
245 });
246});
247
248export const PullRequestsToolkitHandlersLive = PullRequestsToolkit.toLayer(make);