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