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

handlers.ts

348 lines12.6 KB

1import {
2 threadPullRequestsOf,
3 threadPullRequestKeysEqual,
4} from "@t3tools/shared/threadPullRequests";
5import {
6 CommandId,
7 pullRequestHostOf,
8 type OrchestrationProjectShell,
9 type OrchestrationV2ThreadShell,
10 type SourceControlProviderKind,
11 type ThreadId,
12 type ThreadPullRequestLink,
13} from "@t3tools/contracts";
14import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
15import {
16 normalizeThreadPullRequestKey,
17 resolveThreadPullRequestChains,
18 threadPullRequestKeyOf,
19 visibleThreadPullRequests,
20} from "@t3tools/shared/threadPullRequests";
21import * as Cause from "effect/Cause";
22import * as Crypto from "effect/Crypto";
23import * as Effect from "effect/Effect";
24import * as Option from "effect/Option";
25​
26import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
27import * as ProjectService from "../../../project/ProjectService.ts";
28import * as McpInvocationContext from "../../McpInvocationContext.ts";
29import * as McpToolAccess from "../../McpToolAccess.ts";
30import {
31 type ListThreadPullRequestsResult,
32 PullRequestLinkFailedError,
33 PullRequestUrlInvalidError,
34 PullRequestTargetIncompleteError,
35 PullRequestHostRequiredError,
36 PullRequestUnlinkFailedError,
37 PullRequestListFailedError,
38 PullRequestNotOpenError,
39 type PullRequestTargetInput,
40 PullRequestWatchFailedError,
41 PullRequestWatchFromSubagentError,
42 PullRequestThreadNotFoundError,
43 PullRequestThreadRequiredError,
44 PullRequestsToolkit,
45 type ThreadPullRequestEntry,
46} from "./tools.ts";
47​
48interface ResolvedTarget {
49 readonly host: string;
50 readonly repository: string;
51 readonly number: number;
52 readonly url: string;
54​
55/** The project's host and provider supply defaults for a repository-and-number input. */
56function projectHostAndProvider(project: OrchestrationProjectShell | undefined): {
57 readonly host: string | null;
58 readonly kind: SourceControlProviderKind | null;
59} {
60 const identity = project?.repositoryIdentity;
61 const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;
62 if (!identity || kind === null) return { host: null, kind: null };
63 return {
64 host: pullRequestHostOf(identity, kind),
65 kind,
66 };
68​
69/**
70 * Turns whichever shape the agent passed into one host-level identity. A URL
71 * wins outright; otherwise the repository and number are completed with the
72 * thread's project host, which is where an agent working in that checkout
73 * almost always opened the pull request.
74 */
75const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (
76 input: PullRequestTargetInput,
77 project: OrchestrationProjectShell | undefined,
78) {
79 if (input.url !== undefined) {
80 const parsed = parseChangeRequestUrl(input.url);
81 if (parsed === null) {
82 return yield* new PullRequestUrlInvalidError({});
83 }
84 return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;
85 }
86 if (input.repository === undefined || input.number === undefined) {
87 return yield* new PullRequestTargetIncompleteError({});
88 }
89 const projectHost = projectHostAndProvider(project);
90 const host = (input.host ?? projectHost.host)?.toLowerCase();
91 if (host === undefined) {
92 return yield* new PullRequestHostRequiredError({});
93 }
94 const repository = input.repository.toLowerCase();
95 const url =
96 changeRequestUrlFor(
97 // The project's kind only describes its own host; another host gets no URL guess.
98 host === projectHost.host ? projectHost.kind : null,
99 host,
100 repository,
101 input.number,
102 project?.repositoryIdentity?.locator.remoteUrl,
103 ) ?? `https://${host}/${repository}/pull/${input.number}`;
104 return {
105 ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),
106 url,
107 } satisfies ResolvedTarget;
108});
109​
110function entryOf(
111 link: ThreadPullRequestLink,
112 chains: ReturnType<typeof resolveThreadPullRequestChains>,
113): ThreadPullRequestEntry {
114 const key = threadPullRequestKeyOf(link);
115 let stack: ThreadPullRequestEntry["stack"] = null;
116 for (const chain of chains) {
117 if (chain.layers.length < 2) continue;
118 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
119 if (index !== -1) {
120 stack = { kind: chain.kind, position: index + 1, size: chain.layers.length };
121 break;
122 }
123 }
124 return {
125 host: normalizeThreadPullRequestKey(link).host,
126 repository: link.repository,
127 number: link.number,
128 url: link.url,
129 source: link.source,
130 watching: link.watch !== undefined,
131 state: link.snapshot?.state ?? null,
132 title: link.snapshot?.title ?? null,
133 headBranch: link.snapshot?.headBranch ?? null,
134 baseBranch: link.snapshot?.baseBranch ?? null,
135 isDraft: link.snapshot?.isDraft ?? null,
136 stack,
137 };
139​
140/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
141export function listThreadPullRequests(
142 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
143): ListThreadPullRequestsResult {
144 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
145 return {
146 pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) =>
147 entryOf(link, chains),
148 ),
149 chains: chains.map((chain) => ({
150 kind: chain.kind,
151 numbers: chain.layers.map((layer) => layer.number),
152 })),
153 };
155​
156const make = Effect.gen(function* () {
157 const engine = yield* Orchestrator.OrchestratorV2;
158​
159 const projects = yield* ProjectService.ProjectService;
160 const crypto = yield* Crypto.Crypto;
161​
162 const commandId = (tag: string, threadId: ThreadId) =>
163 crypto.randomUUIDv4.pipe(
164 Effect.orDie,
165 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
166 );
167​
168 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
169 Failure:
170 | typeof PullRequestLinkFailedError
171 | typeof PullRequestUnlinkFailedError
172 | typeof PullRequestListFailedError
173 | typeof PullRequestWatchFailedError,
174 requested: ThreadId | undefined,
175 ) {
176 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
177 const threadId = requested ?? scope.thread?.threadId;
178 if (threadId === undefined) {
179 return yield* new PullRequestThreadRequiredError();
180 }
181 const thread = yield* engine
182 .getThreadShell(threadId)
183 .pipe(Effect.map(Option.fromNullishOr))
184 .pipe(Effect.mapError((cause) => new Failure({ cause })));
185 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
186 return yield* new PullRequestThreadNotFoundError({ threadId });
187 }
188 return thread.value;
189 });
190​
191 const projectOf = (
192 thread: OrchestrationV2ThreadShell,
193 Failure:
194 | typeof PullRequestLinkFailedError
195 | typeof PullRequestUnlinkFailedError
196 | typeof PullRequestWatchFailedError,
197 ) =>
198 projects.getShell(thread.projectId).pipe(
199 Effect.map(Option.getOrUndefined),
200 Effect.mapError((cause) => new Failure({ cause })),
201 );
202​
203 const dispatchFailure =
204 (
205 Failure:
206 | typeof PullRequestLinkFailedError
207 | typeof PullRequestUnlinkFailedError
208 | typeof PullRequestWatchFailedError,
209 ) =>
210 <E>(
211 cause: Cause.Cause<E>,
212 ): Effect.Effect<
213 never,
214 PullRequestLinkFailedError | PullRequestUnlinkFailedError | PullRequestWatchFailedError
215 > =>
216 Cause.hasInterruptsOnly(cause)
217 ? Effect.failCause(cause as Cause.Cause<never>)
218 : Effect.fail(new Failure({ cause }));
219​
220 /**
221 * Starts or stops a watch. One command links an unlinked pull request and watches it, and the
222 * result reports the state the thread holds afterwards.
223 */
224 const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (
225 input: PullRequestTargetInput,
226 watching: boolean,
227 ) {
228 const thread = yield* requireThread(PullRequestWatchFailedError, input.threadId);
229 const project = yield* projectOf(thread, PullRequestWatchFailedError);
230 const target = yield* resolveTarget(input, project);
231 const watchedLink = (shell: OrchestrationV2ThreadShell) =>
232 threadPullRequestsOf(shell).find(
233 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
234 );
235 if (watching && thread.lineage.relationshipToParent === "subagent") {
236 return yield* new PullRequestWatchFromSubagentError();
237 }
238 const before = watchedLink(thread);
239 // A merged pull request cannot reopen. A closed one can, and its saved state may be stale,
240 // so the watch starts and its first read ends it if the host still says closed.
241 if (watching && before?.snapshot?.state === "merged") {
242 return yield* new PullRequestNotOpenError({ state: "merged" });
243 }
244 yield* engine
245 .dispatch({
246 type: "thread.pull-request.watch",
247 commandId: yield* commandId("mcp-pr-watch", thread.id),
248 threadId: thread.id,
249 host: target.host,
250 repository: target.repository,
251 number: target.number,
252 watching,
253 ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}),
254 })
255 .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));
256 const after = yield* requireThread(PullRequestWatchFailedError, thread.id);
257 return {
258 host: target.host,
259 repository: target.repository,
260 number: target.number,
261 url: target.url,
262 watching: watchedLink(after)?.watch !== undefined,
263 wasWatching: before?.watch !== undefined,
264 };
265 });
266​
267 /** A tool that changes `threadId`, or the caller's own thread when it is omitted. */
268 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
269 handle: (params: P) => Effect.Effect<A, E, R>,
270 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
271​
272 return {
273 link_pull_request: writesThread((input) =>
274 Effect.gen(function* () {
275 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
276 const project = yield* projectOf(thread, PullRequestLinkFailedError);
277 const target = yield* resolveTarget(input, project);
278 const existing = threadPullRequestsOf(thread).find((link) =>
279 threadPullRequestKeysEqual(link, target),
280 );
281 if (existing && existing.source !== "stack-dismissed")
282 return { ...target, alreadyLinked: true };
283 const alreadyLinked = yield* engine
284 .dispatch({
285 type: "thread.pull-request.link",
286 commandId: yield* commandId("mcp-pr-link", thread.id),
287 threadId: thread.id,
288 host: target.host,
289 repository: target.repository,
290 number: target.number,
291 url: target.url,
292 source: "agent",
293 })
294 .pipe(
295 Effect.as(false),
296 // The decider rejects a second link of the same PR; for the agent that is
297 // the outcome it asked for, not an error.
298​
299 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
300 );
301 return { ...target, alreadyLinked };
302 }),
303 ),
304 unlink_pull_request: writesThread((input) =>
305 Effect.gen(function* () {
306 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
307 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
308 const target = yield* resolveTarget(input, project);
309 if (!threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, target)))
310 return {
311 host: target.host,
312 repository: target.repository,
313 number: target.number,
314 wasLinked: false,
315 };
316 const wasLinked = yield* engine
317 .dispatch({
318 type: "thread.pull-request.unlink",
319 commandId: yield* commandId("mcp-pr-unlink", thread.id),
320 threadId: thread.id,
321 host: target.host,
322 repository: target.repository,
323 number: target.number,
324 })
325 .pipe(
326 Effect.as(true),
327​
328 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
329 );
330 return {
331 host: target.host,
332 repository: target.repository,
333 number: target.number,
334 wasLinked,
335 };
336 }),
337 ),
338 list_thread_pull_requests: McpToolAccess.reads((input) =>
339 requireThread(PullRequestListFailedError, input.threadId).pipe(
340 Effect.map(listThreadPullRequests),
341 ),
342 ),
343 watch_pull_request: writesThread((input) => setWatching(input, true)),
344 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
345 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
346});
347​
348export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);