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

WorktreeMcpService.ts

474 lines18.8 KB

1import {
2 CommandId,
3 MessageId,
4 type ProjectId,
5 WorktreeMcpFailure,
6 type WorktreeMcpContinuationStatus,
7 type WorktreeMcpHandoffInput,
8 type WorktreeMcpHandoffResult,
9 type WorktreeMcpSetupScriptStatus,
10 type WorktreeMcpStatusResult,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as Crypto from "effect/Crypto";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19​
20import * as GitWorkflowService from "../git/GitWorkflowService.ts";
21import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
22import * as ProjectService from "../project/ProjectService.ts";
23import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
26import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
27​
28export class WorktreeMcpService extends Context.Service<
29 WorktreeMcpService,
30 {
31 readonly handoff: (
32 scope: McpInvocationScope,
33 input: WorktreeMcpHandoffInput,
34 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
35 readonly status: (
36 scope: McpInvocationScope,
37 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
38 }
39>()("t3/mcp/WorktreeMcpService") {}
40​
41function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
42 return new WorktreeMcpFailure({ code, message });
44​
45function errorMessage(error: unknown): string {
46 if (error instanceof Error) return error.message;
47 if (typeof error === "object" && error !== null && "message" in error) {
48 return String((error as { message: unknown }).message);
49 }
50 return String(error);
52​
53const asOperationFailed = (prefix: string) =>
54 Effect.mapError((error: unknown) =>
55 failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
56 );
57​
58const make = Effect.gen(function* () {
59 const crypto = yield* Crypto.Crypto;
60 const path = yield* Path.Path;
61 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
62 const projects = yield* ProjectService.ProjectService;
63 const serverSettings = yield* ServerSettings.ServerSettingsService;
64 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
65 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
66 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
67​
68 // Serializes handoffs per thread: two concurrent calls could otherwise both
69 // pass the worktreePath === null check and each create a worktree, leaving
70 // one untracked on disk.
71 const handoffThreadsInFlight = new Set<string>();
72​
73 const requireThreadScope = (scope: McpInvocationScope) =>
74 scope.thread === undefined
75 ? Effect.fail(
76 failure(
77 "thread_credential_required",
78 "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
79 ),
80 )
81 : Effect.succeed(scope as McpThreadInvocationScope);
82​
83 const requireCapability = (scope: McpInvocationScope) =>
84 scope.capabilities.has("worktree")
85 ? Effect.void
86 : Effect.fail(
87 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
88 );
89​
90 const loadThread = (scope: McpThreadInvocationScope) =>
91 threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
92 Effect.mapError((error) =>
93 error._tag === "OrchestratorProjectionError"
94 ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`)
95 : failure(
96 "operation_failed",
97 `Unable to read thread ${scope.thread.threadId}: ${errorMessage(error)}`,
98 ),
99 ),
100 Effect.filterOrFail(
101 (projection) => projection.thread.deletedAt === null,
102 () => failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`),
103 ),
104 );
105​
106 const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
107 projects.getById(projectId).pipe(
108 asOperationFailed(`Unable to read project ${projectId}`),
109 Effect.flatMap(
110 Option.match({
111 onNone: () =>
112 Effect.fail(
113 failure(
114 "project_not_found",
115 `Project '${projectId}' was not found for thread '${scope.thread.threadId}'.`,
116 ),
117 ),
118 onSome: Effect.succeed,
119 }),
120 ),
121 );
122​
123 const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(
124 Effect.map((settings) => settings.newWorktreesStartFromOrigin),
125 asOperationFailed("Unable to read server settings"),
126 );
127​
128 const handoffIds = (scope: McpThreadInvocationScope) =>
129 crypto.randomUUIDv4().pipe(
130 Effect.map((uuid) => {
131 const part = (kind: string, operation: string) =>
132 [kind, "mcp", encodeURIComponent(scope.thread.providerSessionId), operation, uuid].join(
133 ":",
134 );
135 return {
136 commandId: CommandId.make(part("command", "worktree-handoff")),
137 continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
138 continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
139 };
140 }),
141 Effect.orDie,
142 );
143​
144 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
145 scope: McpThreadInvocationScope,
146 input: WorktreeMcpHandoffInput,
147 ) {
148 const alreadyInWorktree = (worktreePath: string) =>
149 failure(
150 "already_in_worktree",
151 `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`,
152 );
153​
154 const projection = yield* loadThread(scope);
155 if (projection.thread.worktreePath !== null) {
156 return yield* alreadyInWorktree(projection.thread.worktreePath);
157 }
158 if (projection.thread.archivedAt !== null) {
159 return yield* failure(
160 "invalid_request",
161 `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`,
162 );
163 }
164​
165 const project = yield* loadProject(scope, projection.thread.projectId);
166 const projectCwd = project.workspaceRoot;
167​
168 if (input.path !== undefined && !path.isAbsolute(input.path)) {
169 return yield* failure(
170 "invalid_request",
171 `path must be an absolute filesystem path, got '${input.path}'. A relative path would be created relative to the project workspace but stored verbatim as the thread's worktree binding.`,
172 );
173 }
174​
175 const localStatus = yield* gitWorkflow
176 .localStatus({ cwd: projectCwd })
177 .pipe(asOperationFailed("Unable to read git status"));
178 if (!localStatus.isRepo) {
179 return yield* failure(
180 "invalid_request",
181 `Project workspace '${projectCwd}' is not a git repository.`,
182 );
183 }
184​
185 const localBranchNames = yield* gitWorkflow
186 .listLocalBranchNames(projectCwd)
187 .pipe(asOperationFailed("Unable to list branches"));
188 if (localBranchNames.includes(input.branch)) {
189 const existingRef = yield* gitWorkflow
190 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
191 .pipe(
192 Effect.map((result) =>
193 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
194 ),
195 Effect.orElseSucceed(() => undefined),
196 );
197 const checkoutPath = existingRef?.worktreePath ?? null;
198 return yield* failure(
199 "invalid_request",
200 `Branch '${input.branch}' already exists${
201 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
202 }. Choose a different branch name, or delete the existing branch${
203 checkoutPath === null ? "" : " and its worktree"
204 } first.`,
205 );
206 }
207​
208 let baseRef = input.baseRef;
209 if (baseRef === undefined) {
210 if (localStatus.refName === null) {
211 return yield* failure(
212 "invalid_request",
213 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
214 );
215 }
216 baseRef = localStatus.refName;
217 }
218​
219 const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
220​
221 let worktreeBaseRef = baseRef;
222 if (startFromOrigin) {
223 yield* gitWorkflow
224 .fetchRemote({ cwd: projectCwd, remoteName: "origin" })
225 .pipe(asOperationFailed("Unable to fetch origin"));
226 const resolvedRemoteBase = yield* gitWorkflow
227 .resolveRemoteTrackingCommit({
228 cwd: projectCwd,
229 refName: baseRef,
230 fallbackRemoteName: "origin",
231 })
232 .pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`));
233 worktreeBaseRef = resolvedRemoteBase.commitSha;
234 }
235​
236 const ids = yield* handoffIds(scope);
237​
238 // uninterruptibleMask: only the potentially slow worktree creation itself
239 // stays interruptible (restore). From the moment it succeeds, through the
240 // binding, continuation queue, setup script launch, and result
241 // construction, there is no interruptible gap: a client cancel can
242 // therefore neither orphan the created worktree before the rollback is
243 // armed, nor skip setting up a worktree the thread was just bound to
244 // (once the binding commits, the scheduled session detach can sever this
245 // request's connection and interrupt the fiber).
246 return yield* Effect.uninterruptibleMask((restore) =>
247 Effect.gen(function* () {
248 const worktree = yield* restore(
249 gitWorkflow
250 .createWorktree({
251 cwd: projectCwd,
252 refName: worktreeBaseRef,
253 newRefName: input.branch,
254 baseRefName: baseRef,
255 path: input.path ?? null,
256 })
257 .pipe(asOperationFailed("Unable to create the worktree")),
258 );
259 const worktreePath = worktree.worktree.path;
260​
261 const reportFailed = (logMessage: string) =>
262 Effect.catchCause((cause: Cause.Cause<unknown>) => {
263 const detail = errorMessage(Cause.squash(cause));
264 return Effect.logWarning(logMessage, {
265 threadId: scope.thread.threadId,
266 worktreePath,
267 detail,
268 }).pipe(Effect.as({ status: "failed", detail } as const));
269 });
270​
271 const removeCreatedWorktree = Effect.suspend(() =>
272 gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
273 Effect.andThen(
274 Effect.suspend(() =>
275 gitWorkflow.deleteLocalBranch({
276 cwd: projectCwd,
277 refName: worktree.worktree.refName,
278 force: true,
279 }),
280 ),
281 ),
282 ),
283 ).pipe(Effect.ignoreCause({ log: true }));
284​
285 const recheckAndBind = Effect.gen(function* () {
286 // The projection was read before the potentially slow git work
287 // above; a concurrent binding (for example from the UI) could have
288 // attached the thread in the meantime. Re-check before committing so
289 // the race cannot leave a second, untracked worktree.
290 const recheck = yield* loadThread(scope);
291 if (recheck.thread.worktreePath !== null) {
292 return yield* alreadyInWorktree(recheck.thread.worktreePath);
293 }
294 if (recheck.thread.archivedAt !== null) {
295 return yield* failure(
296 "invalid_request",
297 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
298 );
299 }
300 yield* threadManagement
301 .dispatch({
302 type: "thread.metadata.update",
303 commandId: ids.commandId,
304 threadId: scope.thread.threadId,
305 branch: worktree.worktree.refName,
306 worktreePath,
307 expectedWorktreePath: null,
308 })
309 .pipe(
310 Effect.catchCause((cause) =>
311 Cause.hasInterruptsOnly(cause)
312 ? Effect.failCause(cause as Cause.Cause<never>)
313 : Effect.fail(
314 failure(
315 "operation_failed",
316 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
317 ),
318 ),
319 ),
320 );
321 }).pipe(
322 // Interrupt-only causes skip the removal: the binding may have
323 // committed, and force-deleting a worktree the thread now points at
324 // would be worse than leaking one.
325 Effect.onError((cause) =>
326 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
327 ),
328 );
329​
330 // Queue the continuation right after the binding commits: the detach
331 // that the metadata update schedules will terminate the calling
332 // session, and a durably queued message is what guarantees the thread
333 // re-launches inside the worktree.
334 const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
335 Effect.suspend(() =>
336 input.continuationPrompt === undefined
337 ? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
338 : threadManagement
339 .sendToThread({
340 projectId: projection.thread.projectId,
341 commandId: ids.continuationCommandId,
342 threadId: scope.thread.threadId,
343 messageId: ids.continuationMessageId,
344 text: input.continuationPrompt,
345 attachments: [],
346 mode: "queue",
347 createdBy: "agent",
348 creationSource: "mcp",
349 })
350 .pipe(
351 Effect.map((sendResult): WorktreeMcpContinuationStatus => ({
352 status: "scheduled",
353 delivery: sendResult.delivery,
354 })),
355 reportFailed("worktree handoff continuation failed to queue"),
356 ),
357 );
358​
359 const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
360​
361 yield* vcsStatusBroadcaster
362 .refreshStatus(worktreePath)
363 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
364​
365 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
366 if (input.runSetupScript ?? true) {
367 setupScript = yield* setupScriptRunner
368 .runForThread({
369 threadId: scope.thread.threadId,
370 projectId: projection.thread.projectId,
371 projectCwd,
372 worktreePath,
373 project: {
374 id: project.id,
375 workspaceRoot: project.workspaceRoot,
376 scripts: project.scripts,
377 },
378 })
379 .pipe(
380 Effect.map((result): WorktreeMcpSetupScriptStatus =>
381 result.status === "started"
382 ? {
383 status: "started",
384 scriptName: result.scriptName,
385 terminalId: result.terminalId,
386 }
387 : { status: "no-script" },
388 ),
389 reportFailed("worktree handoff setup script failed"),
390 );
391 }
392​
393 const result: WorktreeMcpHandoffResult = {
394 worktreePath,
395 branch: worktree.worktree.refName,
396 baseRef,
397 startedFromOrigin: startFromOrigin,
398 setupScript,
399 continuation,
400 note:
401 continuation.status === "scheduled"
402 ? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
403 : "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
404 };
405 return result;
406 }),
407 );
408 });
409​
410 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
411 function* (callerScope, input) {
412 yield* requireCapability(callerScope);
413 const scope = yield* requireThreadScope(callerScope);
414 // uninterruptibleMask: the guard acquisition and the registration of the
415 // releasing finalizer happen with no interruptible gap in between. An
416 // interrupt landing between a bare add() and the start of an ensured
417 // effect would otherwise leak the guard entry and block every future
418 // handoff for this thread until restart.
419 return yield* Effect.uninterruptibleMask((restore) =>
420 Effect.suspend(() => {
421 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
422 return Effect.fail(
423 failure(
424 "handoff_in_progress",
425 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
426 ),
427 );
428 }
429 handoffThreadsInFlight.add(scope.thread.threadId);
430 return restore(performHandoff(scope, input)).pipe(
431 Effect.ensuring(
432 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
433 ),
434 );
435 }),
436 );
437 },
438 );
439​
440 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
441 function* (callerScope) {
442 yield* requireCapability(callerScope);
443 const scope = yield* requireThreadScope(callerScope);
444 const projection = yield* loadThread(scope);
445 const project = yield* loadProject(scope, projection.thread.projectId);
446​
447 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
448​
449 const result: WorktreeMcpStatusResult = {
450 attached: projection.thread.worktreePath !== null,
451 worktreePath: projection.thread.worktreePath,
452 branch: projection.thread.branch,
453 projectWorkspaceRoot: project.workspaceRoot,
454 defaultStartFromOrigin,
455 };
456 return result;
457 },
458 );
459​
460 return WorktreeMcpService.of({ handoff, status });
461});
462​
463export const layer: Layer.Layer<
464 WorktreeMcpService,
465 never,
466 | Crypto.Crypto
467 | Path.Path
468 | ThreadManagementService.ThreadManagementService
469 | ProjectService.ProjectService
470 | ServerSettings.ServerSettingsService
471 | GitWorkflowService.GitWorkflowService
472 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
473 | VcsStatusBroadcaster.VcsStatusBroadcaster
474> = Layer.effect(WorktreeMcpService, make);