Open History to see the last commit
1import {
2 CommandId,
3 type GitCommandError,
4 type TaskFolderError,
5 MessageId,
6 type ProjectId,
7 WorktreeMcpFailure,
8 type WorktreeMcpContinuationStatus,
9 type WorktreeMcpHandoffInput,
10 type WorktreeMcpHandoffResult,
11 type WorktreeMcpSetupScriptStatus,
12 type WorktreeMcpStatusResult,
13 type VcsListRefsInput,
14 type VcsListRefsResult,
15} from "@t3tools/contracts";
16import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import type * as PlatformError from "effect/PlatformError";
25
26import * as GitWorkflowService from "../git/GitWorkflowService.ts";
27import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
28import * as ProjectService from "../project/ProjectService.ts";
29import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
32import * as TaskFolders from "../workspace/TaskFolders.ts";
33import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
34
35export class WorktreeMcpService extends Context.Service<
36 WorktreeMcpService,
37 {
38 readonly handoff: (
39 scope: McpInvocationScope,
40 input: WorktreeMcpHandoffInput,
41 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
42 readonly status: (
43 scope: McpInvocationScope,
44 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
45 readonly listRefs: (
46 input: Omit<VcsListRefsInput, "cwd"> & {
47 readonly worktreePath: string | null;
48 readonly workspaceRoot: string;
49 },
50 ) => Effect.Effect<VcsListRefsResult, GitCommandError | PlatformError.PlatformError>;
51 }
52>()("t3/mcp/WorktreeMcpService") {}
53
54function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
55 return new WorktreeMcpFailure({ code, message });
56}
57
58function errorMessage(error: unknown): string {
59 if (error instanceof Error) return error.message;
60 if (typeof error === "object" && error !== null && "message" in error) {
61 return String((error as { message: unknown }).message);
62 }
63 return String(error);
64}
65
66const asOperationFailed = (prefix: string) =>
67 Effect.mapError((error: unknown) =>
68 failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
69 );
70
71const make = Effect.gen(function* () {
72 const random = yield* SecureRandom.SecureRandom;
73 const fileSystem = yield* FileSystem.FileSystem;
74 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
75 const projects = yield* ProjectService.ProjectService;
76 const serverSettings = yield* ServerSettings.ServerSettingsService;
77 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
78 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
79 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
80 const taskFolders = yield* TaskFolders.TaskFolders;
81 // The administrator's limit, fixed for the server's life as it is where turns start.
82 const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
83
84 // Serialize handoffs per thread to avoid creating two worktrees and orphaning one.
85 const handoffThreadsInFlight = new Set<string>();
86
87 const requireThreadScope = (scope: McpInvocationScope) =>
88 scope.thread === undefined
89 ? Effect.fail(
90 failure(
91 "thread_credential_required",
92 "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
93 ),
94 )
95 : Effect.succeed(scope as McpThreadInvocationScope);
96
97 const requireCapability = (scope: McpInvocationScope) =>
98 scope.capabilities.has("worktree")
99 ? Effect.void
100 : Effect.fail(
101 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
102 );
103
104 const loadThread = (scope: McpThreadInvocationScope) =>
105 threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
106 Effect.mapError((error) =>
107 error._tag === "OrchestratorProjectionError"
108 ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`)
109 : failure(
110 "operation_failed",
111 `Unable to read thread ${scope.thread.threadId}: ${errorMessage(error)}`,
112 ),
113 ),
114 Effect.filterOrFail(
115 (projection) => projection.thread.deletedAt === null,
116 () => failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`),
117 ),
118 );
119
120 const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
121 projects.getById(projectId).pipe(
122 asOperationFailed(`Unable to read project ${projectId}`),
123 Effect.flatMap(
124 Option.match({
125 onNone: () =>
126 Effect.fail(
127 failure(
128 "project_not_found",
129 `Project '${projectId}' was not found for thread '${scope.thread.threadId}'.`,
130 ),
131 ),
132 onSome: Effect.succeed,
133 }),
134 ),
135 );
136
137 const readDefaultStartFromOrigin = (projectId: ProjectId) =>
138 serverSettings.getSettings.pipe(
139 Effect.map(
140 (settings) =>
141 resolveProjectSettings(settings, projectId).settings.newWorktreesStartFromOrigin,
142 ),
143 asOperationFailed("Unable to read server settings"),
144 );
145
146 const handoffIds = (scope: McpThreadInvocationScope) =>
147 random.uuidV4().pipe(
148 Effect.map((uuid) => {
149 const part = (kind: string, operation: string) =>
150 [kind, "mcp", encodeURIComponent(scope.thread.providerSessionId), operation, uuid].join(
151 ":",
152 );
153 return {
154 commandId: CommandId.make(part("command", "worktree-handoff")),
155 continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
156 };
157 }),
158 Effect.orDie,
159 );
160
161 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
162 scope: McpThreadInvocationScope,
163 input: WorktreeMcpHandoffInput,
164 ) {
165 const alreadyInWorktree = (worktreePath: string) =>
166 failure(
167 "already_in_worktree",
168 `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`,
169 );
170
171 const projection = yield* loadThread(scope);
172 if (projection.thread.worktreePath !== null) {
173 return yield* alreadyInWorktree(projection.thread.worktreePath);
174 }
175 if (projection.thread.archivedAt !== null) {
176 return yield* failure(
177 "invalid_request",
178 `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`,
179 );
180 }
181
182 const project = yield* loadProject(scope, projection.thread.projectId);
183 const projectCwd = project.workspaceRoot;
184 // The agent asks, so its thread's modes decide what of the project's own code runs for it:
185 // as they are when each piece is about to run, since the fetch in between can take a while.
186 const projectCommandsNow = loadThread(scope).pipe(
187 Effect.map(({ thread }) =>
188 TaskFolders.projectCommandsForAgent(thread.linkOrigin, thread, maxRuntimeMode),
189 ),
190 // A thread that cannot be read might be below Full access.
191 Effect.orElseSucceed((): TaskFolders.ProjectCommands => "agent-below-full-access"),
192 );
193
194 // A project that tracks repositories moves into a task folder: its own folder, which need
195 // not be a repository, and a worktree of each tracked one.
196 const taskPlan = yield* taskFolders
197 .plan({ projectId: project.id })
198 .pipe(asOperationFailed("Unable to read the project's repositories"));
199 const projectIsRepository = taskPlan === null || taskPlan.projectIsRepository;
200 const localStatus = yield* gitWorkflow
201 .localStatus({ cwd: projectCwd })
202 .pipe(asOperationFailed("Unable to read git status"));
203 if (projectIsRepository && !localStatus.isRepo) {
204 return yield* failure(
205 "invalid_request",
206 `Project workspace '${projectCwd}' is not a git repository.`,
207 );
208 }
209
210 const localBranchNames = projectIsRepository
211 ? yield* gitWorkflow
212 .listLocalBranchNames(projectCwd)
213 .pipe(asOperationFailed("Unable to list branches"))
214 : [];
215 if (localBranchNames.includes(input.branch)) {
216 const existingRef = yield* gitWorkflow
217 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
218 .pipe(
219 Effect.map((result) =>
220 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
221 ),
222 Effect.orElseSucceed(() => undefined),
223 );
224 const checkoutPath = existingRef?.worktreePath ?? null;
225 return yield* failure(
226 "invalid_request",
227 `Branch '${input.branch}' already exists${
228 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
229 }. Choose a different branch name, or delete the existing branch${
230 checkoutPath === null ? "" : " and its worktree"
231 } first.`,
232 );
233 }
234
235 let baseRef = input.baseRef;
236 if (baseRef === undefined && !projectIsRepository) {
237 // Each repository starts from its own default branch.
238 baseRef = "HEAD";
239 } else if (baseRef === undefined) {
240 if (localStatus.refName === null) {
241 return yield* failure(
242 "invalid_request",
243 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
244 );
245 }
246 baseRef = localStatus.refName;
247 }
248
249 const startFromOrigin =
250 input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id));
251
252 let worktreeBaseRef = baseRef;
253 let baseRefName = baseRef;
254 let startedFromOrigin = false;
255 if (startFromOrigin && projectIsRepository) {
256 const resolvedRemoteBase = yield* gitWorkflow
257 .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
258 .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
259 if (resolvedRemoteBase !== null) {
260 worktreeBaseRef = resolvedRemoteBase.commitSha;
261 baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
262 startedFromOrigin = true;
263 }
264 }
265
266 const ids = yield* handoffIds(scope);
267
268 // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller.
269 return yield* Effect.uninterruptibleMask((restore) =>
270 Effect.gen(function* () {
271 const worktree = yield* restore(
272 Effect.suspend(
273 (): Effect.Effect<
274 {
275 readonly path: string;
276 readonly refName: string;
277 readonly taskFolder: string | null;
278 },
279 GitCommandError | TaskFolderError
280 > =>
281 taskPlan === null
282 ? gitWorkflow
283 .createWorktree({
284 cwd: projectCwd,
285 refName: worktreeBaseRef,
286 newRefName: input.branch,
287 baseRefName,
288 path: null,
289 })
290 .pipe(Effect.map((created) => ({ ...created.worktree, taskFolder: null })))
291 : taskFolders
292 .create({
293 plan: taskPlan,
294 branch: input.branch,
295 projectStart: { refName: worktreeBaseRef, baseRefName },
296 baseBranch: input.baseRef,
297 startFromOrigin,
298 projectCommands: projectCommandsNow,
299 })
300 .pipe(
301 Effect.map((created) => {
302 // A layout command is handed the branch name, not the fetched commit.
303 startedFromOrigin =
304 !created.laidOutByProject &&
305 (startedFromOrigin || created.repositoriesStartedFromOrigin);
306 return {
307 path: created.taskFolder.projectPath,
308 refName: created.branch,
309 taskFolder: created.taskFolder.root,
310 };
311 }),
312 ),
313 ).pipe(asOperationFailed("Unable to create the worktree")),
314 );
315 const worktreePath = worktree.path;
316
317 const reportFailed = (logMessage: string) =>
318 Effect.catchCause((cause: Cause.Cause<unknown>) => {
319 const detail = errorMessage(Cause.squash(cause));
320 return Effect.logWarning(logMessage, {
321 threadId: scope.thread.threadId,
322 worktreePath,
323 detail,
324 }).pipe(Effect.as({ status: "failed", detail } as const));
325 });
326
327 const createdTaskFolder = worktree.taskFolder;
328 const removeCreatedWorktree = Effect.suspend(
329 (): Effect.Effect<unknown, GitCommandError | TaskFolderError> =>
330 createdTaskFolder === null
331 ? gitWorkflow
332 .removeWorktree({ cwd: projectCwd, path: worktreePath, force: true })
333 .pipe(
334 Effect.andThen(
335 Effect.suspend(() =>
336 gitWorkflow.deleteLocalBranch({
337 cwd: projectCwd,
338 refName: worktree.refName,
339 force: true,
340 }),
341 ),
342 ),
343 )
344 : taskFolders.remove({
345 root: createdTaskFolder,
346 force: true,
347 forget: true,
348 projectCommands: projectCommandsNow,
349 deleteBranch: worktree.refName,
350 }),
351 ).pipe(Effect.ignoreCause({ log: true }));
352
353 const recheckAndBind = Effect.gen(function* () {
354 // A concurrent UI binding may have landed during git work; do not orphan a second worktree.
355 const recheck = yield* loadThread(scope);
356 if (recheck.thread.worktreePath !== null) {
357 return yield* alreadyInWorktree(recheck.thread.worktreePath);
358 }
359 if (recheck.thread.archivedAt !== null) {
360 return yield* failure(
361 "invalid_request",
362 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
363 );
364 }
365 return yield* threadManagement
366 .dispatch({
367 type: "thread.metadata.update",
368 commandId: ids.commandId,
369 threadId: scope.thread.threadId,
370 branch: worktree.refName,
371 worktreePath,
372 expectedWorktreePath: null,
373 // Binding detaches the session and ends the caller; a later send could lose the race.
374 ...(input.continuationPrompt === undefined
375 ? {}
376 : {
377 continuation: {
378 messageId: ids.continuationMessageId,
379 text: input.continuationPrompt,
380 },
381 }),
382 })
383 .pipe(
384 Effect.catchCause((cause) =>
385 Cause.hasInterruptsOnly(cause)
386 ? Effect.failCause(cause as Cause.Cause<never>)
387 : Effect.fail(
388 failure(
389 "operation_failed",
390 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
391 ),
392 ),
393 ),
394 );
395 }).pipe(
396 // Do not remove on interruption alone; the thread binding may already have committed.
397 Effect.onError((cause) =>
398 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
399 ),
400 );
401
402 const bound = yield* recheckAndBind;
403 const continuation: WorktreeMcpContinuationStatus =
404 input.continuationPrompt === undefined
405 ? { status: "skipped" }
406 : {
407 status: "scheduled",
408 delivery: bound.storedEvents.some(
409 ({ event }) => event.type === "run.created" && event.payload.status !== "queued",
410 )
411 ? "started"
412 : "queued",
413 };
414
415 yield* vcsStatusBroadcaster
416 .refreshStatus(worktreePath)
417 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
418
419 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
420 // The saved setup script is the project's code too: below Full access it waits for a person.
421 const setupWaitsForFullAccess =
422 (input.runSetupScript ?? true) &&
423 (yield* projectCommandsNow) === "agent-below-full-access";
424 if ((input.runSetupScript ?? true) && !setupWaitsForFullAccess) {
425 setupScript = yield* setupScriptRunner
426 .runForThread({
427 threadId: scope.thread.threadId,
428 projectId: projection.thread.projectId,
429 projectCwd,
430 worktreePath,
431 project: {
432 id: project.id,
433 workspaceRoot: project.workspaceRoot,
434 scripts: project.scripts,
435 },
436 })
437 .pipe(
438 Effect.map((result): WorktreeMcpSetupScriptStatus =>
439 result.status === "started"
440 ? {
441 status: "started",
442 scriptName: result.scriptName,
443 terminalId: result.terminalId,
444 }
445 : result.status === "skipped-for-link"
446 ? { status: "skipped" }
447 : { status: "no-script" },
448 ),
449 reportFailed("worktree handoff setup script failed"),
450 );
451 }
452
453 const result: WorktreeMcpHandoffResult = {
454 worktreePath,
455 branch: worktree.refName,
456 baseRef,
457 startedFromOrigin,
458 setupScript,
459 continuation,
460 note: `${
461 continuation.status === "scheduled"
462 ? "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."
463 : "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."
464 }${
465 setupWaitsForFullAccess
466 ? " Project setup scripts do not run for a handoff from a thread below Full access."
467 : ""
468 }`,
469 };
470 return result;
471 }),
472 );
473 });
474
475 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
476 function* (callerScope, input) {
477 yield* requireCapability(callerScope);
478 const scope = yield* requireThreadScope(callerScope);
479 // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart.
480 return yield* Effect.uninterruptibleMask((restore) =>
481 Effect.suspend(() => {
482 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
483 return Effect.fail(
484 failure(
485 "handoff_in_progress",
486 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
487 ),
488 );
489 }
490 handoffThreadsInFlight.add(scope.thread.threadId);
491 return restore(performHandoff(scope, input)).pipe(
492 Effect.ensuring(
493 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
494 ),
495 );
496 }),
497 );
498 },
499 );
500
501 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
502 function* (callerScope) {
503 yield* requireCapability(callerScope);
504 const scope = yield* requireThreadScope(callerScope);
505 const projection = yield* loadThread(scope);
506 const project = yield* loadProject(scope, projection.thread.projectId);
507
508 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin(project.id);
509
510 const result: WorktreeMcpStatusResult = {
511 attached: projection.thread.worktreePath !== null,
512 worktreePath: projection.thread.worktreePath,
513 branch: projection.thread.branch,
514 projectWorkspaceRoot: project.workspaceRoot,
515 defaultStartFromOrigin,
516 };
517 return result;
518 },
519 );
520
521 const listRefs: WorktreeMcpService["Service"]["listRefs"] = Effect.fn(
522 "WorktreeMcpService.listRefs",
523 )(function* ({ worktreePath, workspaceRoot, ...refs }) {
524 // Storage cleanup removes a worktree but keeps its path on the thread.
525 const cwd =
526 worktreePath !== null && (yield* fileSystem.exists(worktreePath))
527 ? worktreePath
528 : workspaceRoot;
529 return yield* gitWorkflow.listRefs({ ...refs, cwd });
530 });
531
532 return WorktreeMcpService.of({ handoff, status, listRefs });
533});
534
535export const layer: Layer.Layer<
536 WorktreeMcpService,
537 never,
538 | SecureRandom.SecureRandom
539 | FileSystem.FileSystem
540 | ThreadManagementService.ThreadManagementService
541 | ProjectService.ProjectService
542 | ServerSettings.ServerSettingsService
543 | GitWorkflowService.GitWorkflowService
544 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
545 | VcsStatusBroadcaster.VcsStatusBroadcaster
546 | TaskFolders.TaskFolders
547> = Layer.effect(WorktreeMcpService, make);