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

WorktreeMcpService.ts

550 lines22.0 KB

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 });
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);
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 yield* TaskFolders.requireSomeRepository(taskPlan).pipe(
200 Effect.mapError((error) => failure("invalid_request", error.detail)),
201 );
202 const projectIsRepository = taskPlan === null || taskPlan.projectIsRepository;
203 const localStatus = yield* gitWorkflow
204 .localStatus({ cwd: projectCwd })
205 .pipe(asOperationFailed("Unable to read git status"));
206 if (projectIsRepository && !localStatus.isRepo) {
207 return yield* failure(
208 "invalid_request",
209 `Project workspace '${projectCwd}' is not a git repository.`,
210 );
211 }
212​
213 const localBranchNames = projectIsRepository
214 ? yield* gitWorkflow
215 .listLocalBranchNames(projectCwd)
216 .pipe(asOperationFailed("Unable to list branches"))
217 : [];
218 if (localBranchNames.includes(input.branch)) {
219 const existingRef = yield* gitWorkflow
220 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
221 .pipe(
222 Effect.map((result) =>
223 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
224 ),
225 Effect.orElseSucceed(() => undefined),
226 );
227 const checkoutPath = existingRef?.worktreePath ?? null;
228 return yield* failure(
229 "invalid_request",
230 `Branch '${input.branch}' already exists${
231 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
232 }. Choose a different branch name, or delete the existing branch${
233 checkoutPath === null ? "" : " and its worktree"
234 } first.`,
235 );
236 }
237​
238 let baseRef = input.baseRef;
239 if (baseRef === undefined && !projectIsRepository) {
240 // Each repository starts from its own default branch.
241 baseRef = "HEAD";
242 } else if (baseRef === undefined) {
243 if (localStatus.refName === null) {
244 return yield* failure(
245 "invalid_request",
246 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
247 );
248 }
249 baseRef = localStatus.refName;
250 }
251​
252 const startFromOrigin =
253 input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id));
254​
255 let worktreeBaseRef = baseRef;
256 let baseRefName = baseRef;
257 let startedFromOrigin = false;
258 if (startFromOrigin && projectIsRepository) {
259 const resolvedRemoteBase = yield* gitWorkflow
260 .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
261 .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
262 if (resolvedRemoteBase !== null) {
263 worktreeBaseRef = resolvedRemoteBase.commitSha;
264 baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
265 startedFromOrigin = true;
266 }
267 }
268​
269 const ids = yield* handoffIds(scope);
270​
271 // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller.
272 return yield* Effect.uninterruptibleMask((restore) =>
273 Effect.gen(function* () {
274 const worktree = yield* restore(
275 Effect.suspend(
276 (): Effect.Effect<
277 {
278 readonly path: string;
279 readonly refName: string;
280 readonly taskFolder: string | null;
281 },
282 GitCommandError | TaskFolderError
283 > =>
284 taskPlan === null
285 ? gitWorkflow
286 .createWorktree({
287 cwd: projectCwd,
288 refName: worktreeBaseRef,
289 newRefName: input.branch,
290 baseRefName,
291 path: null,
292 })
293 .pipe(Effect.map((created) => ({ ...created.worktree, taskFolder: null })))
294 : taskFolders
295 .create({
296 plan: taskPlan,
297 branch: input.branch,
298 projectStart: { refName: worktreeBaseRef, baseRefName },
299 baseBranch: input.baseRef,
300 startFromOrigin,
301 projectCommands: projectCommandsNow,
302 })
303 .pipe(
304 Effect.map((created) => {
305 // A layout command is handed the branch name, not the fetched commit.
306 startedFromOrigin =
307 !created.laidOutByProject &&
308 (startedFromOrigin || created.repositoriesStartedFromOrigin);
309 return {
310 path: created.taskFolder.projectPath,
311 refName: created.branch,
312 taskFolder: created.taskFolder.root,
313 };
314 }),
315 ),
316 ).pipe(asOperationFailed("Unable to create the worktree")),
317 );
318 const worktreePath = worktree.path;
319​
320 const reportFailed = (logMessage: string) =>
321 Effect.catchCause((cause: Cause.Cause<unknown>) => {
322 const detail = errorMessage(Cause.squash(cause));
323 return Effect.logWarning(logMessage, {
324 threadId: scope.thread.threadId,
325 worktreePath,
326 detail,
327 }).pipe(Effect.as({ status: "failed", detail } as const));
328 });
329​
330 const createdTaskFolder = worktree.taskFolder;
331 const removeCreatedWorktree = Effect.suspend(
332 (): Effect.Effect<unknown, GitCommandError | TaskFolderError> =>
333 createdTaskFolder === null
334 ? gitWorkflow
335 .removeWorktree({ cwd: projectCwd, path: worktreePath, force: true })
336 .pipe(
337 Effect.andThen(
338 Effect.suspend(() =>
339 gitWorkflow.deleteLocalBranch({
340 cwd: projectCwd,
341 refName: worktree.refName,
342 force: true,
343 }),
344 ),
345 ),
346 )
347 : taskFolders.remove({
348 root: createdTaskFolder,
349 force: true,
350 forget: true,
351 projectCommands: projectCommandsNow,
352 deleteBranch: worktree.refName,
353 }),
354 ).pipe(Effect.ignoreCause({ log: true }));
355​
356 const recheckAndBind = Effect.gen(function* () {
357 // A concurrent UI binding may have landed during git work; do not orphan a second worktree.
358 const recheck = yield* loadThread(scope);
359 if (recheck.thread.worktreePath !== null) {
360 return yield* alreadyInWorktree(recheck.thread.worktreePath);
361 }
362 if (recheck.thread.archivedAt !== null) {
363 return yield* failure(
364 "invalid_request",
365 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
366 );
367 }
368 return yield* threadManagement
369 .dispatch({
370 type: "thread.metadata.update",
371 commandId: ids.commandId,
372 threadId: scope.thread.threadId,
373 branch: worktree.refName,
374 worktreePath,
375 expectedWorktreePath: null,
376 // Binding detaches the session and ends the caller; a later send could lose the race.
377 ...(input.continuationPrompt === undefined
378 ? {}
379 : {
380 continuation: {
381 messageId: ids.continuationMessageId,
382 text: input.continuationPrompt,
383 },
384 }),
385 })
386 .pipe(
387 Effect.catchCause((cause) =>
388 Cause.hasInterruptsOnly(cause)
389 ? Effect.failCause(cause as Cause.Cause<never>)
390 : Effect.fail(
391 failure(
392 "operation_failed",
393 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
394 ),
395 ),
396 ),
397 );
398 }).pipe(
399 // Do not remove on interruption alone; the thread binding may already have committed.
400 Effect.onError((cause) =>
401 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
402 ),
403 );
404​
405 const bound = yield* recheckAndBind;
406 const continuation: WorktreeMcpContinuationStatus =
407 input.continuationPrompt === undefined
408 ? { status: "skipped" }
409 : {
410 status: "scheduled",
411 delivery: bound.storedEvents.some(
412 ({ event }) => event.type === "run.created" && event.payload.status !== "queued",
413 )
414 ? "started"
415 : "queued",
416 };
417​
418 yield* vcsStatusBroadcaster
419 .refreshStatus(worktreePath)
420 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
421​
422 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
423 // The saved setup script is the project's code too: below Full access it waits for a person.
424 const setupWaitsForFullAccess =
425 (input.runSetupScript ?? true) &&
426 (yield* projectCommandsNow) === "agent-below-full-access";
427 if ((input.runSetupScript ?? true) && !setupWaitsForFullAccess) {
428 setupScript = yield* setupScriptRunner
429 .runForThread({
430 threadId: scope.thread.threadId,
431 projectId: projection.thread.projectId,
432 projectCwd,
433 worktreePath,
434 project: {
435 id: project.id,
436 workspaceRoot: project.workspaceRoot,
437 scripts: project.scripts,
438 },
439 })
440 .pipe(
441 Effect.map((result): WorktreeMcpSetupScriptStatus =>
442 result.status === "started"
443 ? {
444 status: "started",
445 scriptName: result.scriptName,
446 terminalId: result.terminalId,
447 }
448 : result.status === "skipped-for-link"
449 ? { status: "skipped" }
450 : { status: "no-script" },
451 ),
452 reportFailed("worktree handoff setup script failed"),
453 );
454 }
455​
456 const result: WorktreeMcpHandoffResult = {
457 worktreePath,
458 branch: worktree.refName,
459 baseRef,
460 startedFromOrigin,
461 setupScript,
462 continuation,
463 note: `${
464 continuation.status === "scheduled"
465 ? "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."
466 : "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."
467 }${
468 setupWaitsForFullAccess
469 ? " Project setup scripts do not run for a handoff from a thread below Full access."
470 : ""
471 }`,
472 };
473 return result;
474 }),
475 );
476 });
477​
478 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
479 function* (callerScope, input) {
480 yield* requireCapability(callerScope);
481 const scope = yield* requireThreadScope(callerScope);
482 // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart.
483 return yield* Effect.uninterruptibleMask((restore) =>
484 Effect.suspend(() => {
485 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
486 return Effect.fail(
487 failure(
488 "handoff_in_progress",
489 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
490 ),
491 );
492 }
493 handoffThreadsInFlight.add(scope.thread.threadId);
494 return restore(performHandoff(scope, input)).pipe(
495 Effect.ensuring(
496 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
497 ),
498 );
499 }),
500 );
501 },
502 );
503​
504 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
505 function* (callerScope) {
506 yield* requireCapability(callerScope);
507 const scope = yield* requireThreadScope(callerScope);
508 const projection = yield* loadThread(scope);
509 const project = yield* loadProject(scope, projection.thread.projectId);
510​
511 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin(project.id);
512​
513 const result: WorktreeMcpStatusResult = {
514 attached: projection.thread.worktreePath !== null,
515 worktreePath: projection.thread.worktreePath,
516 branch: projection.thread.branch,
517 projectWorkspaceRoot: project.workspaceRoot,
518 defaultStartFromOrigin,
519 };
520 return result;
521 },
522 );
523​
524 const listRefs: WorktreeMcpService["Service"]["listRefs"] = Effect.fn(
525 "WorktreeMcpService.listRefs",
526 )(function* ({ worktreePath, workspaceRoot, ...refs }) {
527 // Storage cleanup removes a worktree but keeps its path on the thread.
528 const cwd =
529 worktreePath !== null && (yield* fileSystem.exists(worktreePath))
530 ? worktreePath
531 : workspaceRoot;
532 return yield* gitWorkflow.listRefs({ ...refs, cwd });
533 });
534​
535 return WorktreeMcpService.of({ handoff, status, listRefs });
536});
537​
538export const layer: Layer.Layer<
539 WorktreeMcpService,
540 never,
541 | SecureRandom.SecureRandom
542 | FileSystem.FileSystem
543 | ThreadManagementService.ThreadManagementService
544 | ProjectService.ProjectService
545 | ServerSettings.ServerSettingsService
546 | GitWorkflowService.GitWorkflowService
547 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
548 | VcsStatusBroadcaster.VcsStatusBroadcaster
549 | TaskFolders.TaskFolders
550> = Layer.effect(WorktreeMcpService, make);