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

handlers.ts

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