The best way to control Claude Code, Codex and more from any computer or phone

main
ts 611 lines 26.9 KB
Raw
1 import {
2 CommandId,
3 MessageId,
4 ThreadId,
5 OrchestratorMcpFailure,
6 type OrchestrationV2ThreadLaunchWorkspaceStrategy,
7 ProjectId,
8 type Project as ProjectRecord,
9 type ServerProvider,
10 T3_PROJECT_FILE_NAME,
11 } from "@t3tools/contracts";
12 import * as Digest from "effect/crypto/Digest";
13 import * as Effect from "effect/Effect";
14 import * as Hex from "effect/encoding/Hex";
15 import * as FileSystem from "effect/FileSystem";
16 import * as Option from "effect/Option";
17 import * as Schema from "effect/Schema";
18 import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
19 import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
20 import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
21 import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
22 import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
23 import * as Project from "../../../project/ProjectService.ts";
24 import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts";
25 import { mutateProjectWithClone } from "../../../project/ProjectMutation.ts";
26 import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
27 import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
28 import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
29 import * as ServerSettings from "../../../serverSettings.ts";
30 import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
31 import * as DateTime from "effect/DateTime";
32 import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
33 import {
34 resolveProjectFileBackedSetting,
35 resolveProjectSettings,
36 } from "@t3tools/shared/projectSettings";
37 import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
38 import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
39 import { resolveRuntimeMode } from "../../delegatedTaskModes.ts";
40 import * as McpInvocationContext from "../../McpInvocationContext.ts";
41 import * as McpToolAccess from "../../McpToolAccess.ts";
42 import * as OrchestrationMcp from "../../OrchestratorMcpService.ts";
43 import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
44 import { ProjectToolkit } from "./tools.ts";
45
46 const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError);
47
48 function projectFailure(error: Project.ProjectServiceError) {
49 if (error._tag === "ProjectOperationError") return unavailable();
50 const message =
51 error._tag === "ProjectInvalidError"
52 ? error.detail
53 : error._tag === "ProjectNotFoundError"
54 ? "The project was not found."
55 : error._tag === "ProjectConflictError"
56 ? "The workspace is already registered to a project."
57 : "The project is not empty; force=true is required to delete it.";
58 return new OrchestratorMcpFailure({ code: "invalid_request", message });
59 }
60
61 function worktreeCheckHint(
62 error:
63 | ThreadLaunch.ThreadLaunchBaseRefError
64 | ThreadLaunch.ThreadLaunchBranchExistsError
65 | ThreadLaunch.ThreadLaunchBranchConflictError
66 | ThreadLaunch.ThreadLaunchNotRepositoryError,
67 strategy: { readonly startFromOrigin?: boolean | undefined },
68 ) {
69 if (error._tag === "ThreadLaunchNotRepositoryError")
70 return `Use workspaceStrategy: {type: "root"}, or pass the projectId of a Git repository.`;
71 if (error._tag === "ThreadLaunchBranchExistsError")
72 return "Pass a branch name that does not exist yet, or omit branch to get a generated name.";
73 if (error._tag === "ThreadLaunchBranchConflictError") {
74 const sibling = error.branch.replaceAll("/", "-");
75 return `Use a name that does not nest under or contain an existing branch${
76 sibling === error.branch ? "" : `, such as "${sibling}"`
77 }.`;
78 }
79 return `Pass a branch, tag, or commit that exists there${
80 strategy.startFromOrigin === true
81 ? "; no remote of the project has it either."
82 : ", or set startFromOrigin:true if it exists only on a remote."
83 }`;
84 }
85
86 /** Require project worktrees so launches cannot target arbitrary host directories. */
87 const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
88 workspaceRoot: string,
89 worktreePath: string,
90 ) {
91 const git = yield* GitVcsDriver.GitVcsDriver;
92 const fileSystem = yield* FileSystem.FileSystem;
93 const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));
94 const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe(
95 Effect.flatMap((paths) => Effect.forEach(paths, real)),
96 Effect.orElseSucceed((): ReadonlyArray<string> => []),
97 );
98 if (!worktrees.includes(yield* real(worktreePath)))
99 return yield* new OrchestratorMcpFailure({
100 code: "invalid_request",
101 message:
102 "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.",
103 });
104 });
105
106 /** The composer falls back to the project's t3.json when no setting picks the mode. */
107 const projectFileThreadEnvMode = Effect.fn("mcp.projectFileThreadEnvMode")(function* (
108 workspaceRoot: string,
109 ) {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const contents = yield* fileSystem
112 .readFileString(`${workspaceRoot}/${T3_PROJECT_FILE_NAME}`)
113 .pipe(Effect.orElseSucceed(() => null));
114 return resolveProjectFileBackedSetting(
115 "defaultThreadEnvMode",
116 null,
117 contents === null ? null : parseT3ProjectFile(contents),
118 ).value;
119 });
120
121 // Anchored to the fatal line: other diagnostics, such as a dubious-ownership refusal, quote the path.
122 const NON_REPOSITORY_FATAL =
123 /^fatal: (?:not a git repository|gitfile does not point to a valid repository)/im;
124
125 /** Branches from the checkout's current branch, as the composer does; a checkout with no commit or a detached HEAD stays shared. */
126 const defaultWorktreeStrategy = Effect.fn("mcp.defaultWorktreeStrategy")(function* (
127 workspaceRoot: string,
128 ): Effect.fn.Return<
129 OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined,
130 OrchestratorMcpFailure,
131 GitVcsDriver.GitVcsDriver
132 > {
133 const git = yield* GitVcsDriver.GitVcsDriver;
134 const unreadable = new OrchestratorMcpFailure({
135 code: "orchestration_error",
136 message:
137 "Could not read the project's current branch for the new worktree. No thread was created. Retry, or pass workspaceStrategy.",
138 });
139 const commit = yield* git
140 .execute({
141 operation: "mcp.defaultWorktreeStrategy",
142 cwd: workspaceRoot,
143 // Not peeled: a branch whose tip object is missing still resolves, so only an unborn HEAD exits 1.
144 args: ["rev-parse", "--verify", "--quiet", "HEAD"],
145 allowNonZeroExit: true,
146 timeoutMs: 5_000,
147 })
148 .pipe(Effect.orElseSucceed(() => null));
149 // Only Git saying "no commit yet" (exit 1) or "not a repository" keeps the launch shared.
150 if (commit?.exitCode === 1 || (commit !== null && NON_REPOSITORY_FATAL.test(commit.stderr)))
151 return undefined;
152 if (commit?.exitCode !== 0) return yield* unreadable;
153 // symbolic-ref skips the index, so a held index lock cannot drop the launch into the shared checkout.
154 const head = yield* git
155 .execute({
156 operation: "mcp.defaultWorktreeStrategy",
157 cwd: workspaceRoot,
158 args: ["symbolic-ref", "--quiet", "--short", "HEAD"],
159 allowNonZeroExit: true,
160 timeoutMs: 5_000,
161 })
162 .pipe(Effect.orElseSucceed(() => null));
163 if (head?.exitCode === 1) return undefined;
164 const branch = head?.exitCode === 0 ? head.stdout.trim() : "";
165 if (branch.length === 0) return yield* unreadable;
166 return { type: "worktree" as const, baseRef: branch };
167 });
168
169 /** A fixed-length id, so a long key fits in the scratch folder name derived from it. */
170 const launchCommandId = Effect.fn("mcp.launchCommandId")(function* (
171 namespace: string,
172 key: string,
173 ) {
174 const crypto = yield* Digest.Digest;
175 // @effect-diagnostics-next-line globalJsonInEffect:off - a JSON pair keeps the caller apart from the key.
176 const bytes = new TextEncoder().encode(JSON.stringify([namespace, key]));
177 const digest = yield* crypto.digest(Digest.sha256, bytes).pipe(Effect.mapError(unavailable));
178 return CommandId.make(`mcp:launch:${Hex.encode(digest)}`);
179 });
180
181 const access = Effect.gen(function* () {
182 yield* readCaller();
183 return yield* Project.ProjectService;
184 });
185
186 /** Settings, not the project record, hold the default model and actions that new threads use. */
187 const withSavedProjectSettings = Effect.gen(function* () {
188 const settings = yield* ServerSettings.ServerSettingsService.pipe(
189 Effect.flatMap((service) => service.getSettings),
190 Effect.mapError(unavailable),
191 );
192 return (project: ProjectRecord) => {
193 const resolved = resolveProjectSettings(settings, project.id, project);
194 return {
195 ...project,
196 defaultModelSelection:
197 resolved.sources.defaultModelSelection === "project"
198 ? resolved.settings.defaultModelSelection
199 : null,
200 scripts: resolveProjectScripts(settings, project),
201 };
202 };
203 });
204
205 // The project is already committed, so a failed Settings read must not report the create as failed.
206 const withSavedProjectSettingsAfterCreate = withSavedProjectSettings.pipe(
207 Effect.orElseSucceed(() => (project: ProjectRecord) => project),
208 );
209
210 export const layer = McpToolAccess.toLayer(ProjectToolkit, {
211 t3_thread_launch: McpToolAccess.startsThreads(
212 (input) => input,
213 (input, { runtimeMode, interactionMode, linkOrigin }) =>
214 Effect.gen(function* () {
215 const scope = yield* McpInvocationContext.McpInvocationContext;
216 const context = yield* readCaller();
217 const { caller } = context;
218 // A retry with the same key replays the first launch: the ids derive
219 // from the caller and the key, and the launch service replays a
220 // command it already accepted.
221 const commandId =
222 input.clientRequestId === undefined
223 ? yield* newCommandId()
224 : yield* launchCommandId(scope.requestNamespace, input.clientRequestId);
225 const threadId = ThreadId.make(commandId);
226 const messageId = MessageId.make(commandId);
227 const attachments = input.attachments ?? [];
228 const schemaProblem =
229 input.outputSchema === undefined
230 ? null
231 : outputRequestProblem(input.outputSchema, {
232 text: input.message ?? "",
233 attachments: input.attachments,
234 });
235 if (schemaProblem !== null || (input.outputSchema !== undefined && !input.message))
236 return yield* new OrchestratorMcpFailure({
237 code: "invalid_request",
238 message: schemaProblem ?? "outputSchema needs a message that asks for the result.",
239 });
240 if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
241 return yield* new OrchestratorMcpFailure({
242 code: "invalid_request",
243 message: "A new thread accepts only pending attachment uploads.",
244 });
245 if (
246 input.scratch === true &&
247 (input.projectId !== undefined || input.workspaceStrategy !== undefined)
248 )
249 return yield* new OrchestratorMcpFailure({
250 code: "invalid_request",
251 message:
252 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",
253 });
254 const projectId =
255 input.scratch === true
256 ? (yield* ManagedProjectFolders.ManagedProjectFolders.pipe(
257 Effect.flatMap((folders) => folders.ensureScratchProject),
258 Effect.mapError(
259 (error) =>
260 new OrchestratorMcpFailure({
261 code: "orchestration_error",
262 message: error.message,
263 }),
264 ),
265 )).projectId
266 : yield* resolveProjectId(context, input.projectId);
267 // A retry of an accepted launch replays it: it keeps the model it started
268 // with and skips the checks only a new launch needs, which the project
269 // may no longer pass, such as a base branch deleted since.
270 const launched =
271 input.clientRequestId === undefined
272 ? null
273 : yield* context.threads.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
274 const launchedModel =
275 launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
276 const replaying = launchedModel !== undefined;
277 if (launched !== null && replaying && launched.projectId !== projectId)
278 return yield* new OrchestratorMcpFailure({
279 code: "invalid_request",
280 message: "A launch retry must use the original project.",
281 });
282 const project =
283 replaying && input.workspaceStrategy?.type !== "existing_worktree"
284 ? undefined
285 : yield* Project.ProjectService.pipe(
286 Effect.flatMap((projects) => projects.getById(projectId)),
287 Effect.mapError(unavailable),
288 Effect.flatMap(
289 Option.match({
290 onNone: () =>
291 Effect.fail(
292 new OrchestratorMcpFailure({
293 code: "invalid_request",
294 message: "The project was not found.",
295 }),
296 ),
297 onSome: Effect.succeed,
298 }),
299 ),
300 );
301 if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree")
302 yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath);
303 if (!replaying && input.modelSelection !== undefined) {
304 const { instanceId, model } = input.modelSelection;
305 const registry = yield* ProviderRegistry.ProviderRegistry;
306 // The thread runs in this folder, whose own provider config can add models.
307 const cwd =
308 input.workspaceStrategy?.type === "existing_worktree"
309 ? input.workspaceStrategy.worktreePath
310 : project?.workspaceRoot;
311 const requireModel = (
312 providers: ReadonlyArray<ServerProvider>,
313 ): Effect.Effect<void, OrchestratorMcpFailure> => {
314 const provider = OrchestrationMcp.withWorkspaceModels(providers, cwd).find(
315 (candidate) => candidate.instanceId === instanceId,
316 );
317 return provider === undefined
318 ? Effect.void
319 : OrchestrationMcp.requireAdvertisedModel(provider, model);
320 };
321 const checked = requireModel(yield* registry.getProviders);
322 yield* cwd === undefined
323 ? checked
324 : checked.pipe(
325 Effect.catchIf(
326 (error) => error.code === "model_unavailable",
327 () =>
328 Project.ProjectService.pipe(
329 Effect.flatMap((projects) => projects.workspaceScanDirectory(cwd)),
330 Effect.flatMap((scanCwd) =>
331 registry.refreshWorkspaceSnapshot({ instanceId, cwd, scanCwd }),
332 ),
333 Effect.flatMap(requireModel),
334 ),
335 ),
336 );
337 }
338 const projectSettings =
339 replaying || project === undefined
340 ? undefined
341 : yield* ServerSettings.ServerSettingsService.pipe(
342 Effect.flatMap((settings) => settings.getSettings),
343 Effect.mapError(unavailable),
344 Effect.map(
345 (settings) => resolveProjectSettings(settings, projectId, project).settings,
346 ),
347 );
348 // An outside caller that names no workspace follows the new-threads-in-a-worktree
349 // default, as the composer does.
350 const requestedStrategy =
351 input.workspaceStrategy === undefined &&
352 caller === undefined &&
353 project !== undefined &&
354 projectSettings !== undefined &&
355 (projectSettings.defaultThreadEnvMode ??
356 (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree"
357 ? yield* defaultWorktreeStrategy(project.workspaceRoot)
358 : input.workspaceStrategy;
359 // An omitted startFromOrigin follows the new-worktree setting, as the composer and
360 // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base.
361 const strategy =
362 projectSettings !== undefined &&
363 requestedStrategy?.type === "worktree" &&
364 requestedStrategy.startFromOrigin === undefined
365 ? {
366 ...requestedStrategy,
367 startFromOrigin: projectSettings.newWorktreesStartFromOrigin,
368 }
369 : requestedStrategy;
370 // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later.
371 if (!replaying && strategy?.type === "worktree")
372 yield* ThreadLaunch.ThreadLaunchService.pipe(
373 Effect.flatMap((launches) =>
374 launches.checkWorktreeBase({ projectId, workspaceStrategy: strategy }),
375 ),
376 Effect.mapError(
377 (error) =>
378 new OrchestratorMcpFailure({
379 code: "invalid_request",
380 message: `${error.message} No thread was created. ${worktreeCheckHint(error, strategy)}`,
381 }),
382 ),
383 );
384 // A caller outside a thread has nothing to inherit, so it starts with the
385 // project's effective defaults, as the composer does. Its mode stays
386 // within the ceiling it was approved with.
387 const projectDefaults = caller === undefined ? projectSettings : undefined;
388 const modelSelection =
389 input.modelSelection ??
390 launchedModel ??
391 caller?.modelSelection ??
392 (projectDefaults
393 ? resolveNewThreadModelSelection({
394 defaultSelection: projectDefaults.defaultModelSelection,
395 fallbackSelection: projectDefaults.fallbackModelSelection,
396 providers: yield* ProviderRegistry.ProviderRegistry.pipe(
397 Effect.flatMap((registry) => registry.getProviders),
398 ),
399 settings: projectDefaults,
400 projectId,
401 now: DateTime.toEpochMillis(yield* DateTime.now),
402 }).selection
403 : null) ??
404 undefined;
405 if (modelSelection === undefined)
406 return yield* new OrchestratorMcpFailure({
407 code: "invalid_request",
408 message:
409 "Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
410 });
411 let startedRuntimeMode =
412 projectDefaults !== undefined && input.runtimeMode === undefined
413 ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe(
414 Effect.orElseSucceed(() => runtimeMode),
415 )
416 : runtimeMode;
417 if (!replaying) {
418 const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders;
419 startedRuntimeMode = yield* resolveRuntimeMode(startedRuntimeMode, input.runtimeMode, {
420 modelSelection,
421 supportedRuntimeModes: providers.find(
422 (provider) => provider.instanceId === modelSelection.instanceId,
423 )?.supportedRuntimeModes,
424 });
425 }
426 const result = yield* ThreadMessageIntake.launchThread({
427 commandId,
428 threadId,
429 projectId,
430 title: input.title,
431 modelSelection,
432 runtimeMode: startedRuntimeMode,
433 interactionMode,
434 workspaceStrategy: strategy ?? { type: "root" },
435 ...(input.message === undefined && attachments.length === 0
436 ? {}
437 : {
438 initialMessage: {
439 messageId,
440 ...(caller === undefined ? {} : { senderThreadId: caller.id }),
441 text: input.message ?? "",
442 attachments,
443 ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
444 },
445 }),
446 createdBy: "agent",
447 creationSource: "mcp",
448 ...(linkOrigin === undefined ? {} : { linkOrigin }),
449 // Kept only alongside linkOrigin: thread.create drops it otherwise.
450 ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
451 }).pipe(
452 Effect.mapError((error) => {
453 if (error._tag === "AttachmentClaimError") {
454 return new OrchestratorMcpFailure({
455 code: "orchestration_error",
456 message: error.message,
457 });
458 }
459 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
460 return new OrchestratorMcpFailure({
461 code: "invalid_request",
462 message: error.message,
463 });
464 }
465 // The administrator's ceiling refuses the mode; say so rather than "unavailable".
466 if (error._tag === "ThreadLaunchError" && isAboveCeilingError(error.cause)) {
467 return new OrchestratorMcpFailure({
468 code: "invalid_request",
469 message: error.cause.message,
470 });
471 }
472 return unavailable();
473 }),
474 );
475 const thread = result.projection.thread;
476 const run = result.projection.runs.find((run) => run.userMessageId === messageId);
477 return {
478 threadId: thread.id,
479 link: McpInvocationContext.threadLinkFor(scope, thread.id, thread.title),
480 projectId: thread.projectId,
481 modelSelection: thread.modelSelection,
482 runId: run?.id ?? null,
483 status: run?.status ?? null,
484 };
485 }),
486 // The launched thread carries the caller's link, if it has one.
487 "stamped",
488 ),
489 t3_project_list: McpToolAccess.reads((input) =>
490 Effect.gen(function* () {
491 const projects = yield* access;
492 // Identities are resolved: linked environments find this side's project by repository.
493 const page = yield* projects
494 .listPage({ cursor: input.cursor ?? 0, limit: input.limit ?? 20 })
495 .pipe(Effect.mapError(unavailable));
496 return { ...page, projects: page.projects.map(yield* withSavedProjectSettings) };
497 }),
498 ),
499 t3_project_read: McpToolAccess.reads((input) =>
500 Effect.gen(function* () {
501 const projects = yield* access;
502 const result = yield* projects.getById(input.projectId).pipe(Effect.mapError(unavailable));
503 if (Option.isNone(result))
504 return yield* new OrchestratorMcpFailure({
505 code: "invalid_request",
506 message: "The project was not found.",
507 });
508 return (yield* withSavedProjectSettings)(result.value);
509 }),
510 ),
511 t3_project_create: McpToolAccess.writesEnvironment(
512 ({ workspaceRoot, ...input }) =>
513 Effect.gen(function* () {
514 const projects = yield* Project.ProjectService;
515 if (workspaceRoot === undefined) {
516 // Only updates record model defaults; reject defaults that creation would silently drop.
517 if (
518 input.scripts !== undefined ||
519 input.createWorkspaceRootIfMissing !== undefined ||
520 input.defaultModelSelection !== undefined
521 )
522 return yield* new OrchestratorMcpFailure({
523 code: "invalid_request",
524 message:
525 "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
526 });
527 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
528 const created = yield* folders.createNamedProject({ name: input.title }).pipe(
529 Effect.mapError(
530 (error) =>
531 new OrchestratorMcpFailure({
532 code: "orchestration_error",
533 message: error.message,
534 }),
535 ),
536 );
537 const project = yield* projects
538 .getById(created.projectId)
539 .pipe(
540 Effect.mapError(unavailable),
541 Effect.flatMap(
542 Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
543 ),
544 );
545 return {
546 ...(yield* withSavedProjectSettingsAfterCreate)(project),
547 ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
548 };
549 }
550 if (input.defaultModelSelection !== undefined && input.defaultModelSelection !== null)
551 return yield* new OrchestratorMcpFailure({
552 code: "invalid_request",
553 message:
554 "Creating a project does not set its default model; set defaultModelSelection afterwards with t3_project_update.",
555 });
556 const commandId = yield* newCommandId();
557 const created = yield* projects
558 .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
559 .pipe(Effect.mapError(projectFailure));
560 return (yield* withSavedProjectSettingsAfterCreate)(created);
561 }),
562 // Linked work may bring the repository it works in; an existing
563 // registered workspace is still refused.
564 { linkedCallers: "allowed" },
565 ),
566 t3_project_update: McpToolAccess.writesEnvironment((input) =>
567 Effect.gen(function* () {
568 const projects = yield* Project.ProjectService;
569 const updated = yield* projects
570 .update({ ...input, commandId: yield* newCommandId() })
571 .pipe(Effect.mapError(projectFailure));
572 return (yield* withSavedProjectSettings)(updated);
573 }),
574 ),
575 t3_project_delete: McpToolAccess.writesEnvironment((input) =>
576 Effect.gen(function* () {
577 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
578 if (yield* folders.isScratchProject(input.projectId))
579 return yield* new OrchestratorMcpFailure({
580 code: "invalid_request",
581 message:
582 '"No project" is the built-in scratch project and cannot be deleted through MCP. The user can remove it in Settings.',
583 });
584 const projects = yield* Project.ProjectService;
585 const clones = yield* ProjectCloneTracker.ProjectCloneTracker;
586 return yield* mutateProjectWithClone(projects, clones, {
587 ...input,
588 type: "project.delete",
589 commandId: yield* newCommandId(),
590 }).pipe(Effect.mapError(projectFailure));
591 }),
592 ),
593 t3_project_clone: McpToolAccess.writesEnvironment(
594 (input) =>
595 Effect.gen(function* () {
596 const repositories = yield* Repositories.SourceControlRepositoryService;
597 // Agents' MCP calls have their own long budget, and an aborted call interrupts git.
598 return yield* repositories.cloneRepository(input, { timeoutMs: null }).pipe(
599 Effect.mapError(
600 (error) =>
601 new OrchestratorMcpFailure({
602 code: "orchestration_error",
603 message: error.detail,
604 }),
605 ),
606 );
607 }),
608 // An existing destination is never adopted.
609 { linkedCallers: "allowed" },
610 ),
611 });