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