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

WorktreeMcpService.ts

444 lines17.3 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 SecureRandom from "effect/crypto/SecureRandom";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18​
19import * as GitWorkflowService from "../git/GitWorkflowService.ts";
20import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
21import * as ProjectService from "../project/ProjectService.ts";
22import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
23import * as ServerSettings from "../serverSettings.ts";
24import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
25import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
26​
27export class WorktreeMcpService extends Context.Service<
28 WorktreeMcpService,
29 {
30 readonly handoff: (
31 scope: McpInvocationScope,
32 input: WorktreeMcpHandoffInput,
33 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
34 readonly status: (
35 scope: McpInvocationScope,
36 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
37 }
38>()("t3/mcp/WorktreeMcpService") {}
39​
40function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
41 return new WorktreeMcpFailure({ code, message });
43​
44function errorMessage(error: unknown): string {
45 if (error instanceof Error) return error.message;
46 if (typeof error === "object" && error !== null && "message" in error) {
47 return String((error as { message: unknown }).message);
48 }
49 return String(error);
51​
52const asOperationFailed = (prefix: string) =>
53 Effect.mapError((error: unknown) =>
54 failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
55 );
56​
57const make = Effect.gen(function* () {
58 const random = yield* SecureRandom.SecureRandom;
59 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
60 const projects = yield* ProjectService.ProjectService;
61 const serverSettings = yield* ServerSettings.ServerSettingsService;
62 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
63 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
64 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
65​
66 // Serialize handoffs per thread to avoid creating two worktrees and orphaning one.
67 const handoffThreadsInFlight = new Set<string>();
68​
69 const requireThreadScope = (scope: McpInvocationScope) =>
70 scope.thread === undefined
71 ? Effect.fail(
72 failure(
73 "thread_credential_required",
74 "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
75 ),
76 )
77 : Effect.succeed(scope as McpThreadInvocationScope);
78​
79 const requireCapability = (scope: McpInvocationScope) =>
80 scope.capabilities.has("worktree")
81 ? Effect.void
82 : Effect.fail(
83 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
84 );
85​
86 const loadThread = (scope: McpThreadInvocationScope) =>
87 threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
88 Effect.mapError((error) =>
89 error._tag === "OrchestratorProjectionError"
90 ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`)
91 : failure(
92 "operation_failed",
93 `Unable to read thread ${scope.thread.threadId}: ${errorMessage(error)}`,
94 ),
95 ),
96 Effect.filterOrFail(
97 (projection) => projection.thread.deletedAt === null,
98 () => failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`),
99 ),
100 );
101​
102 const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
103 projects.getById(projectId).pipe(
104 asOperationFailed(`Unable to read project ${projectId}`),
105 Effect.flatMap(
106 Option.match({
107 onNone: () =>
108 Effect.fail(
109 failure(
110 "project_not_found",
111 `Project '${projectId}' was not found for thread '${scope.thread.threadId}'.`,
112 ),
113 ),
114 onSome: Effect.succeed,
115 }),
116 ),
117 );
118​
119 const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(
120 Effect.map((settings) => settings.newWorktreesStartFromOrigin),
121 asOperationFailed("Unable to read server settings"),
122 );
123​
124 const handoffIds = (scope: McpThreadInvocationScope) =>
125 random.uuidV4().pipe(
126 Effect.map((uuid) => {
127 const part = (kind: string, operation: string) =>
128 [kind, "mcp", encodeURIComponent(scope.thread.providerSessionId), operation, uuid].join(
129 ":",
130 );
131 return {
132 commandId: CommandId.make(part("command", "worktree-handoff")),
133 continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
134 continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
135 };
136 }),
137 Effect.orDie,
138 );
139​
140 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
141 scope: McpThreadInvocationScope,
142 input: WorktreeMcpHandoffInput,
143 ) {
144 const alreadyInWorktree = (worktreePath: string) =>
145 failure(
146 "already_in_worktree",
147 `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`,
148 );
149​
150 const projection = yield* loadThread(scope);
151 if (projection.thread.worktreePath !== null) {
152 return yield* alreadyInWorktree(projection.thread.worktreePath);
153 }
154 if (projection.thread.archivedAt !== null) {
155 return yield* failure(
156 "invalid_request",
157 `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`,
158 );
159 }
160​
161 const project = yield* loadProject(scope, projection.thread.projectId);
162 const projectCwd = project.workspaceRoot;
163​
164 const localStatus = yield* gitWorkflow
165 .localStatus({ cwd: projectCwd })
166 .pipe(asOperationFailed("Unable to read git status"));
167 if (!localStatus.isRepo) {
168 return yield* failure(
169 "invalid_request",
170 `Project workspace '${projectCwd}' is not a git repository.`,
171 );
172 }
173​
174 const localBranchNames = yield* gitWorkflow
175 .listLocalBranchNames(projectCwd)
176 .pipe(asOperationFailed("Unable to list branches"));
177 if (localBranchNames.includes(input.branch)) {
178 const existingRef = yield* gitWorkflow
179 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
180 .pipe(
181 Effect.map((result) =>
182 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
183 ),
184 Effect.orElseSucceed(() => undefined),
185 );
186 const checkoutPath = existingRef?.worktreePath ?? null;
187 return yield* failure(
188 "invalid_request",
189 `Branch '${input.branch}' already exists${
190 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
191 }. Choose a different branch name, or delete the existing branch${
192 checkoutPath === null ? "" : " and its worktree"
193 } first.`,
194 );
195 }
196​
197 let baseRef = input.baseRef;
198 if (baseRef === undefined) {
199 if (localStatus.refName === null) {
200 return yield* failure(
201 "invalid_request",
202 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
203 );
204 }
205 baseRef = localStatus.refName;
206 }
207​
208 const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
209​
210 let worktreeBaseRef = baseRef;
211 let baseRefName = baseRef;
212 let startedFromOrigin = false;
213 if (startFromOrigin) {
214 const resolvedRemoteBase = yield* gitWorkflow
215 .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
216 .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
217 if (resolvedRemoteBase !== null) {
218 worktreeBaseRef = resolvedRemoteBase.commitSha;
219 baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
220 startedFromOrigin = true;
221 }
222 }
223​
224 const ids = yield* handoffIds(scope);
225​
226 // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller.
227 return yield* Effect.uninterruptibleMask((restore) =>
228 Effect.gen(function* () {
229 const worktree = yield* restore(
230 gitWorkflow
231 .createWorktree({
232 cwd: projectCwd,
233 refName: worktreeBaseRef,
234 newRefName: input.branch,
235 baseRefName,
236 path: null,
237 })
238 .pipe(asOperationFailed("Unable to create the worktree")),
239 );
240 const worktreePath = worktree.worktree.path;
241​
242 const reportFailed = (logMessage: string) =>
243 Effect.catchCause((cause: Cause.Cause<unknown>) => {
244 const detail = errorMessage(Cause.squash(cause));
245 return Effect.logWarning(logMessage, {
246 threadId: scope.thread.threadId,
247 worktreePath,
248 detail,
249 }).pipe(Effect.as({ status: "failed", detail } as const));
250 });
251​
252 const removeCreatedWorktree = Effect.suspend(() =>
253 gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
254 Effect.andThen(
255 Effect.suspend(() =>
256 gitWorkflow.deleteLocalBranch({
257 cwd: projectCwd,
258 refName: worktree.worktree.refName,
259 force: true,
260 }),
261 ),
262 ),
263 ),
264 ).pipe(Effect.ignoreCause({ log: true }));
265​
266 const recheckAndBind = Effect.gen(function* () {
267 // A concurrent UI binding may have landed during git work; do not orphan a second worktree.
268 const recheck = yield* loadThread(scope);
269 if (recheck.thread.worktreePath !== null) {
270 return yield* alreadyInWorktree(recheck.thread.worktreePath);
271 }
272 if (recheck.thread.archivedAt !== null) {
273 return yield* failure(
274 "invalid_request",
275 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
276 );
277 }
278 yield* threadManagement
279 .dispatch({
280 type: "thread.metadata.update",
281 commandId: ids.commandId,
282 threadId: scope.thread.threadId,
283 branch: worktree.worktree.refName,
284 worktreePath,
285 expectedWorktreePath: null,
286 })
287 .pipe(
288 Effect.catchCause((cause) =>
289 Cause.hasInterruptsOnly(cause)
290 ? Effect.failCause(cause as Cause.Cause<never>)
291 : Effect.fail(
292 failure(
293 "operation_failed",
294 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
295 ),
296 ),
297 ),
298 );
299 }).pipe(
300 // Do not remove on interruption alone; the thread binding may already have committed.
301 Effect.onError((cause) =>
302 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
303 ),
304 );
305​
306 // Queue continuation immediately after binding; detachment terminates the caller, so relaunch needs a durable message.
307 const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
308 Effect.suspend(() =>
309 input.continuationPrompt === undefined
310 ? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
311 : threadManagement
312 .sendToThread({
313 projectId: projection.thread.projectId,
314 commandId: ids.continuationCommandId,
315 threadId: scope.thread.threadId,
316 messageId: ids.continuationMessageId,
317 text: input.continuationPrompt,
318 attachments: [],
319 mode: "queue",
320 createdBy: "agent",
321 creationSource: "mcp",
322 })
323 .pipe(
324 Effect.map((sendResult): WorktreeMcpContinuationStatus => ({
325 status: "scheduled",
326 delivery: sendResult.delivery,
327 })),
328 reportFailed("worktree handoff continuation failed to queue"),
329 ),
330 );
331​
332 const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
333​
334 yield* vcsStatusBroadcaster
335 .refreshStatus(worktreePath)
336 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
337​
338 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
339 if (input.runSetupScript ?? true) {
340 setupScript = yield* setupScriptRunner
341 .runForThread({
342 threadId: scope.thread.threadId,
343 projectId: projection.thread.projectId,
344 projectCwd,
345 worktreePath,
346 project: {
347 id: project.id,
348 workspaceRoot: project.workspaceRoot,
349 scripts: project.scripts,
350 },
351 })
352 .pipe(
353 Effect.map((result): WorktreeMcpSetupScriptStatus =>
354 result.status === "started"
355 ? {
356 status: "started",
357 scriptName: result.scriptName,
358 terminalId: result.terminalId,
359 }
360 : result.status === "skipped-for-link"
361 ? { status: "skipped" }
362 : { status: "no-script" },
363 ),
364 reportFailed("worktree handoff setup script failed"),
365 );
366 }
367​
368 const result: WorktreeMcpHandoffResult = {
369 worktreePath,
370 branch: worktree.worktree.refName,
371 baseRef,
372 startedFromOrigin,
373 setupScript,
374 continuation,
375 note:
376 continuation.status === "scheduled"
377 ? "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."
378 : "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.",
379 };
380 return result;
381 }),
382 );
383 });
384​
385 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
386 function* (callerScope, input) {
387 yield* requireCapability(callerScope);
388 const scope = yield* requireThreadScope(callerScope);
389 // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart.
390 return yield* Effect.uninterruptibleMask((restore) =>
391 Effect.suspend(() => {
392 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
393 return Effect.fail(
394 failure(
395 "handoff_in_progress",
396 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
397 ),
398 );
399 }
400 handoffThreadsInFlight.add(scope.thread.threadId);
401 return restore(performHandoff(scope, input)).pipe(
402 Effect.ensuring(
403 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
404 ),
405 );
406 }),
407 );
408 },
409 );
410​
411 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
412 function* (callerScope) {
413 yield* requireCapability(callerScope);
414 const scope = yield* requireThreadScope(callerScope);
415 const projection = yield* loadThread(scope);
416 const project = yield* loadProject(scope, projection.thread.projectId);
417​
418 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
419​
420 const result: WorktreeMcpStatusResult = {
421 attached: projection.thread.worktreePath !== null,
422 worktreePath: projection.thread.worktreePath,
423 branch: projection.thread.branch,
424 projectWorkspaceRoot: project.workspaceRoot,
425 defaultStartFromOrigin,
426 };
427 return result;
428 },
429 );
430​
431 return WorktreeMcpService.of({ handoff, status });
432});
433​
434export const layer: Layer.Layer<
435 WorktreeMcpService,
436 never,
437 | SecureRandom.SecureRandom
438 | ThreadManagementService.ThreadManagementService
439 | ProjectService.ProjectService
440 | ServerSettings.ServerSettingsService
441 | GitWorkflowService.GitWorkflowService
442 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
443 | VcsStatusBroadcaster.VcsStatusBroadcaster
444> = Layer.effect(WorktreeMcpService, make);