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

WorktreeMcpService.ts

463 lines18.4 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";
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 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 let baseRefName = baseRef;
214 let startedFromOrigin = false;
215 if (startFromOrigin) {
216 const resolvedRemoteBase = yield* gitWorkflow
217 .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
218 .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
219 if (resolvedRemoteBase !== null) {
220 worktreeBaseRef = resolvedRemoteBase.commitSha;
221 baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
222 startedFromOrigin = true;
223 }
224 }
225​
226 const ids = yield* handoffIds(scope);
227​
228 // uninterruptibleMask: only the potentially slow worktree creation itself
229 // stays interruptible (restore). From the moment it succeeds, through the
230 // binding, continuation queue, setup script launch, and result
231 // construction, there is no interruptible gap: a client cancel can
232 // therefore neither orphan the created worktree before the rollback is
233 // armed, nor skip setting up a worktree the thread was just bound to
234 // (once the binding commits, the scheduled session detach can sever this
235 // request's connection and interrupt the fiber).
236 return yield* Effect.uninterruptibleMask((restore) =>
237 Effect.gen(function* () {
238 const worktree = yield* restore(
239 gitWorkflow
240 .createWorktree({
241 cwd: projectCwd,
242 refName: worktreeBaseRef,
243 newRefName: input.branch,
244 baseRefName,
245 path: null,
246 })
247 .pipe(asOperationFailed("Unable to create the worktree")),
248 );
249 const worktreePath = worktree.worktree.path;
250​
251 const reportFailed = (logMessage: string) =>
252 Effect.catchCause((cause: Cause.Cause<unknown>) => {
253 const detail = errorMessage(Cause.squash(cause));
254 return Effect.logWarning(logMessage, {
255 threadId: scope.thread.threadId,
256 worktreePath,
257 detail,
258 }).pipe(Effect.as({ status: "failed", detail } as const));
259 });
260​
261 const removeCreatedWorktree = Effect.suspend(() =>
262 gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
263 Effect.andThen(
264 Effect.suspend(() =>
265 gitWorkflow.deleteLocalBranch({
266 cwd: projectCwd,
267 refName: worktree.worktree.refName,
268 force: true,
269 }),
270 ),
271 ),
272 ),
273 ).pipe(Effect.ignoreCause({ log: true }));
274​
275 const recheckAndBind = Effect.gen(function* () {
276 // The projection was read before the potentially slow git work
277 // above; a concurrent binding (for example from the UI) could have
278 // attached the thread in the meantime. Re-check before committing so
279 // the race cannot leave a second, untracked worktree.
280 const recheck = yield* loadThread(scope);
281 if (recheck.thread.worktreePath !== null) {
282 return yield* alreadyInWorktree(recheck.thread.worktreePath);
283 }
284 if (recheck.thread.archivedAt !== null) {
285 return yield* failure(
286 "invalid_request",
287 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
288 );
289 }
290 yield* threadManagement
291 .dispatch({
292 type: "thread.metadata.update",
293 commandId: ids.commandId,
294 threadId: scope.thread.threadId,
295 branch: worktree.worktree.refName,
296 worktreePath,
297 expectedWorktreePath: null,
298 })
299 .pipe(
300 Effect.catchCause((cause) =>
301 Cause.hasInterruptsOnly(cause)
302 ? Effect.failCause(cause as Cause.Cause<never>)
303 : Effect.fail(
304 failure(
305 "operation_failed",
306 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
307 ),
308 ),
309 ),
310 );
311 }).pipe(
312 // Interrupt-only causes skip the removal: the binding may have
313 // committed, and force-deleting a worktree the thread now points at
314 // would be worse than leaking one.
315 Effect.onError((cause) =>
316 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
317 ),
318 );
319​
320 // Queue the continuation right after the binding commits: the detach
321 // that the metadata update schedules will terminate the calling
322 // session, and a durably queued message is what guarantees the thread
323 // re-launches inside the worktree.
324 const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
325 Effect.suspend(() =>
326 input.continuationPrompt === undefined
327 ? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
328 : threadManagement
329 .sendToThread({
330 projectId: projection.thread.projectId,
331 commandId: ids.continuationCommandId,
332 threadId: scope.thread.threadId,
333 messageId: ids.continuationMessageId,
334 text: input.continuationPrompt,
335 attachments: [],
336 mode: "queue",
337 createdBy: "agent",
338 creationSource: "mcp",
339 })
340 .pipe(
341 Effect.map((sendResult): WorktreeMcpContinuationStatus => ({
342 status: "scheduled",
343 delivery: sendResult.delivery,
344 })),
345 reportFailed("worktree handoff continuation failed to queue"),
346 ),
347 );
348​
349 const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
350​
351 yield* vcsStatusBroadcaster
352 .refreshStatus(worktreePath)
353 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
354​
355 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
356 if (input.runSetupScript ?? true) {
357 setupScript = yield* setupScriptRunner
358 .runForThread({
359 threadId: scope.thread.threadId,
360 projectId: projection.thread.projectId,
361 projectCwd,
362 worktreePath,
363 project: {
364 id: project.id,
365 workspaceRoot: project.workspaceRoot,
366 scripts: project.scripts,
367 },
368 })
369 .pipe(
370 Effect.map((result): WorktreeMcpSetupScriptStatus =>
371 result.status === "started"
372 ? {
373 status: "started",
374 scriptName: result.scriptName,
375 terminalId: result.terminalId,
376 }
377 : { status: "no-script" },
378 ),
379 reportFailed("worktree handoff setup script failed"),
380 );
381 }
382​
383 const result: WorktreeMcpHandoffResult = {
384 worktreePath,
385 branch: worktree.worktree.refName,
386 baseRef,
387 startedFromOrigin,
388 setupScript,
389 continuation,
390 note:
391 continuation.status === "scheduled"
392 ? "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."
393 : "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.",
394 };
395 return result;
396 }),
397 );
398 });
399​
400 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
401 function* (callerScope, input) {
402 yield* requireCapability(callerScope);
403 const scope = yield* requireThreadScope(callerScope);
404 // uninterruptibleMask: the guard acquisition and the registration of the
405 // releasing finalizer happen with no interruptible gap in between. An
406 // interrupt landing between a bare add() and the start of an ensured
407 // effect would otherwise leak the guard entry and block every future
408 // handoff for this thread until restart.
409 return yield* Effect.uninterruptibleMask((restore) =>
410 Effect.suspend(() => {
411 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
412 return Effect.fail(
413 failure(
414 "handoff_in_progress",
415 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
416 ),
417 );
418 }
419 handoffThreadsInFlight.add(scope.thread.threadId);
420 return restore(performHandoff(scope, input)).pipe(
421 Effect.ensuring(
422 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
423 ),
424 );
425 }),
426 );
427 },
428 );
429​
430 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
431 function* (callerScope) {
432 yield* requireCapability(callerScope);
433 const scope = yield* requireThreadScope(callerScope);
434 const projection = yield* loadThread(scope);
435 const project = yield* loadProject(scope, projection.thread.projectId);
436​
437 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
438​
439 const result: WorktreeMcpStatusResult = {
440 attached: projection.thread.worktreePath !== null,
441 worktreePath: projection.thread.worktreePath,
442 branch: projection.thread.branch,
443 projectWorkspaceRoot: project.workspaceRoot,
444 defaultStartFromOrigin,
445 };
446 return result;
447 },
448 );
449​
450 return WorktreeMcpService.of({ handoff, status });
451});
452​
453export const layer: Layer.Layer<
454 WorktreeMcpService,
455 never,
456 | Crypto.Crypto
457 | ThreadManagementService.ThreadManagementService
458 | ProjectService.ProjectService
459 | ServerSettings.ServerSettingsService
460 | GitWorkflowService.GitWorkflowService
461 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
462 | VcsStatusBroadcaster.VcsStatusBroadcaster
463> = Layer.effect(WorktreeMcpService, make);