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

handlers.ts

393 lines17.0 KB

1import {
2 CommandId,
3 MessageId,
4 ThreadId,
5 OrchestratorMcpFailure,
6 ProjectId,
7} from "@t3tools/contracts";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as Hex from "effect/encoding/Hex";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
15import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
16import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
17import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
18import * as Project from "../../../project/ProjectService.ts";
19import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts";
20import { mutateProjectWithClone } from "../../../project/ProjectMutation.ts";
21import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
22import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
23import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
24import * as ServerSettings from "../../../serverSettings.ts";
25import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
26import * as DateTime from "effect/DateTime";
27import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
28import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
29import { resolveRuntimeMode } from "../../delegatedTaskModes.ts";
30import * as McpInvocationContext from "../../McpInvocationContext.ts";
31import * as McpToolAccess from "../../McpToolAccess.ts";
32import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
33import { ProjectToolkit } from "./tools.ts";
34​
35const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError);
36​
37function projectFailure(error: Project.ProjectServiceError) {
38 if (error._tag === "ProjectOperationError") return unavailable();
39 const message =
40 error._tag === "ProjectNotFoundError"
41 ? "The project was not found."
42 : error._tag === "ProjectConflictError"
43 ? "The workspace is already registered to a project."
44 : "The project is not empty; force=true is required to delete it.";
45 return new OrchestratorMcpFailure({ code: "invalid_request", message });
47​
48/** Require project worktrees so launches cannot target arbitrary host directories. */
49const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
50 workspaceRoot: string,
51 worktreePath: string,
52) {
53 const git = yield* GitVcsDriver.GitVcsDriver;
54 const fileSystem = yield* FileSystem.FileSystem;
55 const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));
56 const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe(
57 Effect.flatMap((paths) => Effect.forEach(paths, real)),
58 Effect.orElseSucceed((): ReadonlyArray<string> => []),
59 );
60 if (!worktrees.includes(yield* real(worktreePath)))
61 return yield* new OrchestratorMcpFailure({
62 code: "invalid_request",
63 message:
64 "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.",
65 });
66});
67​
68/** A fixed-length id, so a long key fits in the scratch folder name derived from it. */
69const launchCommandId = Effect.fn("mcp.launchCommandId")(function* (
70 namespace: string,
71 key: string,
72) {
73 const crypto = yield* Crypto.Crypto;
74 // @effect-diagnostics-next-line preferSchemaOverJson:off - a JSON pair keeps the caller apart from the key.
75 const bytes = new TextEncoder().encode(JSON.stringify([namespace, key]));
76 const digest = yield* crypto.digest("SHA-256", bytes).pipe(Effect.mapError(unavailable));
77 return CommandId.make(`mcp:launch:${Hex.encode(digest)}`);
78});
79​
80const access = Effect.gen(function* () {
81 yield* readCaller();
82 return yield* Project.ProjectService;
83});
84export const layer = McpToolAccess.toLayer(ProjectToolkit, {
85 t3_thread_launch: McpToolAccess.startsThreads(
86 (input) => input,
87 (input, { runtimeMode, interactionMode, linkOrigin }) =>
88 Effect.gen(function* () {
89 const scope = yield* McpInvocationContext.McpInvocationContext;
90 const context = yield* readCaller();
91 const { caller } = context;
92 // A retry with the same key replays the first launch: the ids derive
93 // from the caller and the key, and the launch service replays a
94 // command it already accepted.
95 const commandId =
96 input.clientRequestId === undefined
97 ? yield* newCommandId()
98 : yield* launchCommandId(scope.requestNamespace, input.clientRequestId);
99 const threadId = ThreadId.make(commandId);
100 const messageId = MessageId.make(commandId);
101 const attachments = input.attachments ?? [];
102 if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
103 return yield* new OrchestratorMcpFailure({
104 code: "invalid_request",
105 message: "A new thread accepts only pending attachment uploads.",
106 });
107 if (
108 input.scratch === true &&
109 (input.projectId !== undefined || input.workspaceStrategy !== undefined)
110 )
111 return yield* new OrchestratorMcpFailure({
112 code: "invalid_request",
113 message:
114 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",
115 });
116 const projectId =
117 input.scratch === true
118 ? (yield* ManagedProjectFolders.ManagedProjectFolders.pipe(
119 Effect.flatMap((folders) => folders.ensureScratchProject),
120 Effect.mapError(
121 (error) =>
122 new OrchestratorMcpFailure({
123 code: "orchestration_error",
124 message: error.message,
125 }),
126 ),
127 )).projectId
128 : yield* resolveProjectId(context, input.projectId);
129 const readProject = Project.ProjectService.pipe(
130 Effect.flatMap((projects) => projects.getById(projectId)),
131 Effect.mapError(unavailable),
132 Effect.map(Option.getOrUndefined),
133 );
134 // A retry of an accepted launch replays it: it keeps the model it started
135 // with and skips the checks only a new launch needs, which the project
136 // may no longer pass, such as a base branch deleted since.
137 const launched =
138 input.clientRequestId === undefined
139 ? null
140 : yield* context.threads.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
141 const launchedModel =
142 launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
143 const replaying = launchedModel !== undefined;
144 if (!replaying && input.workspaceStrategy?.type === "existing_worktree") {
145 const project = yield* readProject;
146 if (project === undefined)
147 return yield* new OrchestratorMcpFailure({
148 code: "invalid_request",
149 message: "The project was not found.",
150 });
151 yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath);
152 }
153 // Reject unresolved base refs before accepting a launch; worktree provisioning happens later.
154 const strategy = input.workspaceStrategy;
155 if (!replaying && strategy?.type === "worktree")
156 yield* ThreadLaunch.ThreadLaunchService.pipe(
157 Effect.flatMap((launches) =>
158 launches.checkWorktreeBase({ projectId, workspaceStrategy: strategy }),
159 ),
160 Effect.mapError(
161 (error) =>
162 new OrchestratorMcpFailure({
163 code: "invalid_request",
164 message: `${error.message} No thread was created. Pass a branch, tag, or commit that exists there${
165 strategy.startFromOrigin === true
166 ? "; the project has no usable remote to fetch it from."
167 : ", or set startFromOrigin:true if it exists only on a remote."
168 }`,
169 }),
170 ),
171 );
172 // A caller outside a thread has nothing to inherit, so it starts with the
173 // project's effective defaults, as the composer does. Its mode stays
174 // within the ceiling it was approved with.
175 const projectDefaults =
176 caller === undefined && !replaying
177 ? yield* ServerSettings.ServerSettingsService.pipe(
178 Effect.flatMap((settings) => settings.getSettings),
179 Effect.mapError(unavailable),
180 Effect.flatMap((settings) =>
181 Effect.map(
182 readProject,
183 (project) => resolveProjectSettings(settings, projectId, project).settings,
184 ),
185 ),
186 )
187 : undefined;
188 const modelSelection =
189 input.modelSelection ??
190 launchedModel ??
191 caller?.modelSelection ??
192 (projectDefaults
193 ? resolveNewThreadModelSelection({
194 defaultSelection: projectDefaults.defaultModelSelection,
195 fallbackSelection: projectDefaults.fallbackModelSelection,
196 providers: yield* ProviderRegistry.ProviderRegistry.pipe(
197 Effect.flatMap((registry) => registry.getProviders),
198 ),
199 settings: projectDefaults,
200 projectId,
201 now: DateTime.toEpochMillis(yield* DateTime.now),
202 }).selection
203 : null) ??
204 undefined;
205 if (modelSelection === undefined)
206 return yield* new OrchestratorMcpFailure({
207 code: "invalid_request",
208 message:
209 "Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.",
210 });
211 let startedRuntimeMode =
212 projectDefaults !== undefined && input.runtimeMode === undefined
213 ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe(
214 Effect.orElseSucceed(() => runtimeMode),
215 )
216 : runtimeMode;
217 if (!replaying) {
218 const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders;
219 startedRuntimeMode = yield* resolveRuntimeMode(startedRuntimeMode, input.runtimeMode, {
220 modelSelection,
221 supportedRuntimeModes: providers.find(
222 (provider) => provider.instanceId === modelSelection.instanceId,
223 )?.supportedRuntimeModes,
224 });
225 }
226 const result = yield* ThreadMessageIntake.launchThread({
227 commandId,
228 threadId,
229 projectId,
230 title: input.title,
231 modelSelection,
232 runtimeMode: startedRuntimeMode,
233 interactionMode,
234 workspaceStrategy: input.workspaceStrategy ?? { type: "root" },
235 ...(input.message === undefined && attachments.length === 0
236 ? {}
237 : {
238 initialMessage: {
239 messageId,
240 ...(caller === undefined ? {} : { senderThreadId: caller.id }),
241 text: input.message ?? "",
242 attachments,
243 },
244 }),
245 createdBy: "agent",
246 creationSource: "mcp",
247 ...(linkOrigin === undefined ? {} : { linkOrigin }),
248 // Kept only alongside linkOrigin: thread.create drops it otherwise.
249 ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
250 }).pipe(
251 Effect.mapError((error) => {
252 if (error._tag === "AttachmentClaimError") {
253 return new OrchestratorMcpFailure({
254 code: "orchestration_error",
255 message: error.message,
256 });
257 }
258 if (error._tag === "ThreadManagementProviderInstanceDisabledError") {
259 return new OrchestratorMcpFailure({
260 code: "invalid_request",
261 message: error.message,
262 });
263 }
264 // The administrator's ceiling refuses the mode; say so rather than "unavailable".
265 if (error._tag === "ThreadLaunchError" && isAboveCeilingError(error.cause)) {
266 return new OrchestratorMcpFailure({
267 code: "invalid_request",
268 message: error.cause.message,
269 });
270 }
271 return unavailable();
272 }),
273 );
274 const thread = result.projection.thread;
275 const run = result.projection.runs.find((run) => run.userMessageId === messageId);
276 return {
277 threadId: thread.id,
278 link: McpInvocationContext.threadLinkFor(scope, thread.id),
279 projectId: thread.projectId,
280 modelSelection: thread.modelSelection,
281 runId: run?.id ?? null,
282 status: run?.status ?? null,
283 };
284 }),
285 // The launched thread carries the caller's link, if it has one.
286 "stamped",
287 ),
288 t3_project_list: McpToolAccess.reads((input) =>
289 Effect.gen(function* () {
290 const projects = yield* access;
291 // Identities are resolved: linked environments find this side's project by repository.
292 return yield* projects
293 .listPage({ cursor: input.cursor ?? 0, limit: input.limit ?? 20 })
294 .pipe(Effect.mapError(unavailable));
295 }),
296 ),
297 t3_project_read: McpToolAccess.reads((input) =>
298 Effect.gen(function* () {
299 const projects = yield* access;
300 const result = yield* projects.getById(input.projectId).pipe(Effect.mapError(unavailable));
301 if (Option.isNone(result))
302 return yield* new OrchestratorMcpFailure({
303 code: "invalid_request",
304 message: "The project was not found.",
305 });
306 return result.value;
307 }),
308 ),
309 t3_project_create: McpToolAccess.writesEnvironment(
310 ({ workspaceRoot, ...input }) =>
311 Effect.gen(function* () {
312 const projects = yield* Project.ProjectService;
313 if (workspaceRoot === undefined) {
314 // Only updates record model defaults; reject defaults that creation would silently drop.
315 if (
316 input.scripts !== undefined ||
317 input.createWorkspaceRootIfMissing !== undefined ||
318 input.defaultModelSelection !== undefined
319 )
320 return yield* new OrchestratorMcpFailure({
321 code: "invalid_request",
322 message:
323 "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
324 });
325 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
326 const created = yield* folders.createNamedProject({ name: input.title }).pipe(
327 Effect.mapError(
328 (error) =>
329 new OrchestratorMcpFailure({
330 code: "orchestration_error",
331 message: error.message,
332 }),
333 ),
334 );
335 const project = yield* projects
336 .getById(created.projectId)
337 .pipe(
338 Effect.mapError(unavailable),
339 Effect.flatMap(
340 Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
341 ),
342 );
343 return {
344 ...project,
345 ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
346 };
347 }
348 const commandId = yield* newCommandId();
349 return yield* projects
350 .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
351 .pipe(Effect.mapError(projectFailure));
352 }),
353 // Linked work may bring the repository it works in; an existing
354 // registered workspace is still refused.
355 { linkedCallers: "allowed" },
356 ),
357 t3_project_update: McpToolAccess.writesEnvironment((input) =>
358 Effect.gen(function* () {
359 const projects = yield* Project.ProjectService;
360 return yield* projects
361 .update({ ...input, commandId: yield* newCommandId() })
362 .pipe(Effect.mapError(projectFailure));
363 }),
364 ),
365 t3_project_delete: McpToolAccess.writesEnvironment((input) =>
366 Effect.gen(function* () {
367 const projects = yield* Project.ProjectService;
368 const clones = yield* ProjectCloneTracker.ProjectCloneTracker;
369 return yield* mutateProjectWithClone(projects, clones, {
370 ...input,
371 type: "project.delete",
372 commandId: yield* newCommandId(),
373 }).pipe(Effect.mapError(projectFailure));
374 }),
375 ),
376 t3_project_clone: McpToolAccess.writesEnvironment(
377 (input) =>
378 Effect.gen(function* () {
379 const repositories = yield* Repositories.SourceControlRepositoryService;
380 return yield* repositories.cloneRepository(input).pipe(
381 Effect.mapError(
382 (error) =>
383 new OrchestratorMcpFailure({
384 code: "orchestration_error",
385 message: error.detail,
386 }),
387 ),
388 );
389 }),
390 // An existing destination is never adopted.
391 { linkedCallers: "allowed" },
392 ),
393});