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

tools.ts

426 lines16.3 KB

1import {
2 McpCapabilityUnavailableError,
3 OrchestratorMcpFailure,
4 PositiveInt,
5 PullRequestReviewGuide,
6 PullRequestReviewGuideRun,
7 PullRequestState,
8 ThreadPullRequestLinkSource,
9 TrimmedNonEmptyString,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Schema from "effect/Schema";
13import * as Tool from "effect/ai/Tool";
14import * as Toolkit from "effect/ai/Toolkit";
15​
16import * as McpInvocationContext from "../../McpInvocationContext.ts";
17import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
18import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
19import * as ProjectService from "../../../project/ProjectService.ts";
20import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
21​
22const dependencies = [
23 McpInvocationContext.McpInvocationContext,
24 ThreadManagementService.ThreadManagementService,
25 Orchestrator.OrchestratorV2,
26 ProjectService.ProjectService,
27];
28​
29const guideDependencies = [
30 ...dependencies,
31 PullRequestReviewGuideService.PullRequestReviewGuideService,
32];
33​
34const REGISTER_EVERY_PR =
35 "Register every pull request you open for this thread, including each layer of a stack, right after creating it.";
36​
37export const PullRequestTargetInput = Schema.Struct({
38 threadId: Schema.optional(
39 ThreadId.annotate({
40 description: "Thread to act on. Omit for this thread.",
41 }),
42 ),
43 url: Schema.optional(
44 TrimmedNonEmptyString.annotate({
45 description:
46 "The pull request's web URL as its host shows it, for example https://git.example.com/owner/repo/pull/123 or https://git.example.com/group/project/-/merge_requests/123. Preferred when you have it; host, repository and number are read from it.",
47 }),
48 ),
49 repository: Schema.optional(
50 TrimmedNonEmptyString.annotate({
51 description:
52 "Repository path below the host, for example owner/repo. Required with number when url is omitted.",
53 }),
54 ),
55 number: Schema.optional(
56 PositiveInt.annotate({
57 description: "Pull request number. Required with repository when url is omitted.",
58 }),
59 ),
60 host: Schema.optional(
61 TrimmedNonEmptyString.annotate({
62 description:
63 "Host the repository lives on, for example git.example.com. Defaults to the host of this thread's project.",
64 }),
65 ),
66});
67export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;
68​
69export class PullRequestUrlInvalidError extends Schema.TaggedError<PullRequestUrlInvalidError>()(
70 "PullRequestUrlInvalidError",
71 {},
72) {
73 override get message(): string {
74 return "This is not a recognised pull request URL. Pass repository and number instead.";
75 }
77​
78export class PullRequestTargetIncompleteError extends Schema.TaggedError<PullRequestTargetIncompleteError>()(
79 "PullRequestTargetIncompleteError",
80 {},
81) {
82 override get message(): string {
83 return "Pass either url, or both repository and number.";
84 }
86​
87export class PullRequestHostRequiredError extends Schema.TaggedError<PullRequestHostRequiredError>()(
88 "PullRequestHostRequiredError",
89 {},
90) {
91 override get message(): string {
92 return "This thread's project has no recognised remote. Pass host or url.";
93 }
95​
96export class PullRequestUrlUnavailableError extends Schema.TaggedError<PullRequestUrlUnavailableError>()(
97 "PullRequestUrlUnavailableError",
98 {},
99) {
100 override get message(): string {
101 return "This thread's project is on a host with no known pull request URL shape. Pass url.";
102 }
104​
105export class PullRequestThreadRequiredError extends Schema.TaggedError<PullRequestThreadRequiredError>()(
106 "PullRequestThreadRequiredError",
107 {},
108) {
109 override get message(): string {
110 return "Pass threadId: this MCP client is not running inside a T3 thread.";
111 }
113​
114export class PullRequestThreadNotFoundError extends Schema.TaggedError<PullRequestThreadNotFoundError>()(
115 "PullRequestThreadNotFoundError",
116 { threadId: Schema.String },
117) {
118 override get message(): string {
119 return `Thread ${this.threadId} was not found.`;
120 }
122​
123export class PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(
124 "PullRequestLinkFailedError",
125 { cause: Schema.Defect() },
126) {
127 override get message(): string {
128 return "Could not link the pull request.";
129 }
131​
132export class PullRequestUnlinkFailedError extends Schema.TaggedError<PullRequestUnlinkFailedError>()(
133 "PullRequestUnlinkFailedError",
134 { cause: Schema.Defect() },
135) {
136 override get message(): string {
137 return "Could not unlink the pull request.";
138 }
140​
141export class PullRequestWatchFailedError extends Schema.TaggedError<PullRequestWatchFailedError>()(
142 "PullRequestWatchFailedError",
143 { cause: Schema.Defect() },
144) {
145 override get message(): string {
146 return "Could not change whether the pull request is watched.";
147 }
149​
150export class PullRequestNotOpenError extends Schema.TaggedError<PullRequestNotOpenError>()(
151 "PullRequestNotOpenError",
152 { state: Schema.String },
153) {
154 override get message(): string {
155 return `The pull request is ${this.state}, so there is nothing to watch.`;
156 }
158​
159export class PullRequestWatchFromSubagentError extends Schema.TaggedError<PullRequestWatchFromSubagentError>()(
160 "PullRequestWatchFromSubagentError",
161 {},
162) {
163 override get message(): string {
164 return "This thread is a subagent, so it cannot watch pull requests. Its parent thread owns the pull request: finish your task and report back instead.";
165 }
167​
168export class PullRequestListFailedError extends Schema.TaggedError<PullRequestListFailedError>()(
169 "PullRequestListFailedError",
170 { cause: Schema.Defect() },
171) {
172 override get message(): string {
173 return "Could not list the pull request.";
174 }
176​
177export class PullRequestProjectNotFoundError extends Schema.TaggedError<PullRequestProjectNotFoundError>()(
178 "PullRequestProjectNotFoundError",
179 { repository: Schema.String },
180) {
181 override get message(): string {
182 return `No project in this environment is a checkout of ${this.repository}, so its pull requests cannot be read here. Add one with t3_project_create.`;
183 }
185​
186export class PullRequestGuideFailedError extends Schema.TaggedError<PullRequestGuideFailedError>()(
187 "PullRequestGuideFailedError",
188 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
189) {
190 override get message(): string {
191 return this.detail;
192 }
194​
195export const PullRequestToolError = Schema.Union([
196 OrchestratorMcpFailure,
197 McpCapabilityUnavailableError,
198 PullRequestUrlInvalidError,
199 PullRequestTargetIncompleteError,
200 PullRequestHostRequiredError,
201 PullRequestUrlUnavailableError,
202 PullRequestThreadRequiredError,
203 PullRequestThreadNotFoundError,
204 PullRequestLinkFailedError,
205 PullRequestUnlinkFailedError,
206 PullRequestListFailedError,
207 PullRequestWatchFailedError,
208 PullRequestNotOpenError,
209 PullRequestWatchFromSubagentError,
210 PullRequestProjectNotFoundError,
211 PullRequestGuideFailedError,
212]);
213export type PullRequestToolError = typeof PullRequestToolError.Type;
214​
215const PullRequestIdentity = {
216 host: Schema.String,
217 repository: Schema.String,
218 number: Schema.Int,
219 url: Schema.String,
220};
221​
222export const LinkPullRequestResult = Schema.Struct({
223 ...PullRequestIdentity,
224 alreadyLinked: Schema.Boolean.annotate({
225 description: "True when the pull request was linked to this thread before the call.",
226 }),
227});
228export type LinkPullRequestResult = typeof LinkPullRequestResult.Type;
229​
230export const UnlinkPullRequestResult = Schema.Struct({
231 host: Schema.String,
232 repository: Schema.String,
233 number: Schema.Int,
234 wasLinked: Schema.Boolean.annotate({
235 description: "False when the pull request was not linked to this thread to begin with.",
236 }),
237});
238export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type;
239​
240export const WatchPullRequestResult = Schema.Struct({
241 ...PullRequestIdentity,
242 watching: Schema.Boolean.annotate({
243 description: "Whether T3 Code now watches the pull request for this thread.",
244 }),
245 wasWatching: Schema.Boolean.annotate({
246 description: "Whether it was already watched before the call.",
247 }),
248});
249export type WatchPullRequestResult = typeof WatchPullRequestResult.Type;
250​
251export const ThreadPullRequestEntry = Schema.Struct({
252 ...PullRequestIdentity,
253 source: ThreadPullRequestLinkSource,
254 watching: Schema.Boolean,
255 state: Schema.NullOr(PullRequestState),
256 title: Schema.NullOr(Schema.String),
257 headBranch: Schema.NullOr(Schema.String),
258 baseBranch: Schema.NullOr(Schema.String),
259 isDraft: Schema.NullOr(Schema.Boolean),
260 stack: Schema.NullOr(
261 Schema.Struct({
262 kind: Schema.Literals(["native", "derived"]),
263 /** 1-based layer from the bottom; siblings share a layer. */
264 position: Schema.Int,
265 size: Schema.Int,
266 }),
267 ),
268});
269export type ThreadPullRequestEntry = typeof ThreadPullRequestEntry.Type;
270​
271export const ListThreadPullRequestsResult = Schema.Struct({
272 pullRequests: Schema.Array(ThreadPullRequestEntry),
273 chains: Schema.Array(
274 Schema.Struct({
275 kind: Schema.Literals(["native", "derived"]),
276 /** Bottom to top; each pull request comes before the ones built on it. */
277 numbers: Schema.Array(Schema.Int),
278 }),
279 ),
280});
281export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type;
282​
283const LinkPullRequestTool = Tool.make("link_pull_request", {
284 description: `${REGISTER_EVERY_PR} Links a pull request to this thread so T3 Code tracks it, shows its status beside the thread, and settles the thread when it merges. Pass the URL, or repository plus number. Linking an already-linked pull request succeeds with alreadyLinked=true.`,
285 parameters: PullRequestTargetInput,
286 success: LinkPullRequestResult,
287 failure: PullRequestToolError,
288 dependencies,
289})
290 .annotate(Tool.Title, "Link pull request to thread")
291 .annotate(Tool.Readonly, false)
292 .annotate(Tool.Destructive, false)
293 .annotate(Tool.Idempotent, true)
294 .annotate(Tool.OpenWorld, false);
295​
296const UnlinkPullRequestTool = Tool.make("unlink_pull_request", {
297 description:
298 "Remove a pull request link from this thread, for example after closing a pull request you opened by mistake. Pass the URL, or repository plus number. Unlinking a pull request that is not linked succeeds with wasLinked=false.",
299 parameters: PullRequestTargetInput,
300 success: UnlinkPullRequestResult,
301 failure: PullRequestToolError,
302 dependencies,
303})
304 .annotate(Tool.Title, "Unlink pull request from thread")
305 .annotate(Tool.Readonly, false)
306 .annotate(Tool.Destructive, true)
307 .annotate(Tool.Idempotent, true)
308 .annotate(Tool.OpenWorld, false);
309​
310const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
311 description: `List the pull requests linked to a thread (omit threadId for this thread) with their last known host state, and how they chain into stacks (bottom to top). ${REGISTER_EVERY_PR}`,
312 parameters: Schema.Struct({
313 threadId: Schema.optional(
314 ThreadId.annotate({ description: "Thread to list. Omit for this thread." }),
315 ),
316 }),
317 success: ListThreadPullRequestsResult,
318 failure: PullRequestToolError,
319 dependencies,
320})
321 .annotate(Tool.Title, "List thread pull requests")
322 .annotate(Tool.Readonly, true)
323 .annotate(Tool.Destructive, false)
324 .annotate(Tool.Idempotent, true)
325 .annotate(Tool.OpenWorld, false);
326​
327const WatchPullRequestTool = Tool.make("watch_pull_request", {
328 description:
329 "Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch. A subagent cannot watch: its parent thread owns the pull request.",
330 parameters: PullRequestTargetInput,
331 success: WatchPullRequestResult,
332 failure: PullRequestToolError,
333 dependencies,
334})
335 .annotate(Tool.Title, "Watch pull request")
336 .annotate(Tool.Readonly, false)
337 .annotate(Tool.Destructive, false)
338 .annotate(Tool.Idempotent, true)
339 .annotate(Tool.OpenWorld, false);
340​
341const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", {
342 description:
343 "Stop T3 Code from watching a pull request for this thread. The pull request stays linked. Pass the URL, or repository plus number.",
344 parameters: PullRequestTargetInput,
345 success: WatchPullRequestResult,
346 failure: PullRequestToolError,
347 dependencies,
348})
349 .annotate(Tool.Title, "Stop watching pull request")
350 .annotate(Tool.Readonly, false)
351 .annotate(Tool.Destructive, false)
352 .annotate(Tool.Idempotent, true)
353 .annotate(Tool.OpenWorld, false);
354​
355const GuideTarget = Schema.Struct({
356 url: PullRequestTargetInput.fields.url,
357 repository: PullRequestTargetInput.fields.repository,
358 number: PullRequestTargetInput.fields.number,
359 host: PullRequestTargetInput.fields.host,
360});
361​
362const GuideOutcome = Schema.Struct({
363 ...PullRequestIdentity,
364 outcome: Schema.Literals(["started", "running", "failed"]).annotate({
365 description:
366 "started: a run began. running: one was already going for this head and the call joined it. failed: this pull request could not be guided; see detail.",
367 }),
368 detail: Schema.NullOr(Schema.String),
369});
370​
371export const WritePullRequestGuidesResult = Schema.Struct({
372 guides: Schema.Array(GuideOutcome),
373});
374export type WritePullRequestGuidesResult = typeof WritePullRequestGuidesResult.Type;
375​
376export const ReadPullRequestGuideResult = Schema.Struct({
377 ...PullRequestIdentity,
378 guide: Schema.NullOr(PullRequestReviewGuide),
379 run: Schema.NullOr(PullRequestReviewGuideRun),
380 currentHeadSha: Schema.NullOr(Schema.String),
381 stale: Schema.Boolean.annotate({
382 description:
383 "True when the guide was written for an earlier head than the pull request has now.",
384 }),
385});
386export type ReadPullRequestGuideResult = typeof ReadPullRequestGuideResult.Type;
387​
388const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
389 description:
390 "Write review guides for up to 20 pull requests, the tour a maintainer reads in a pull request's Guide tab. Each run reads its change in a temporary checkout and takes minutes, so this returns once the runs are under way; read a guide with read_pull_request_guide to see when it is written. A guide for the same head that is already running is joined, not restarted; a pull request whose guide is current is written again. Each pull request is read through the project in this environment whose checkout has that repository. Fails while review guides are off on this server.",
391 parameters: Schema.Struct({
392 pullRequests: Schema.Array(GuideTarget).check(Schema.isMinLength(1), Schema.isMaxLength(20)),
393 }),
394 success: WritePullRequestGuidesResult,
395 failure: PullRequestToolError,
396 dependencies: guideDependencies,
397})
398 .annotate(Tool.Title, "Write pull request guides")
399 .annotate(Tool.Readonly, false)
400 .annotate(Tool.Destructive, false)
401 .annotate(Tool.Idempotent, false)
402 .annotate(Tool.OpenWorld, true);
403​
404const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
405 description:
406 "Read a pull request's stored review guide and its run: run.Running while one is being written, run.Failed with the reason when the last one failed, guide null when none was written. stale is true after a push the guide has not caught up with. Never starts a run.",
407 parameters: GuideTarget,
408 success: ReadPullRequestGuideResult,
409 failure: PullRequestToolError,
410 dependencies: guideDependencies,
411})
412 .annotate(Tool.Title, "Read pull request guide")
413 .annotate(Tool.Readonly, true)
414 .annotate(Tool.Destructive, false)
415 .annotate(Tool.Idempotent, true)
416 .annotate(Tool.OpenWorld, true);
417​
418export const PullRequestsToolkit = Toolkit.make(
419 LinkPullRequestTool,
420 UnlinkPullRequestTool,
421 ListThreadPullRequestsTool,
422 WatchPullRequestTool,
423 UnwatchPullRequestTool,
424 WritePullRequestGuidesTool,
425 ReadPullRequestGuideTool,
426);