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

handlers.ts

209 lines8.3 KB

1import { MessageId, ThreadId, OrchestratorMcpFailure, ProjectId } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
5import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
6import * as Project from "../../../project/ProjectService.ts";
7import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
8import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
9import { newCommandId, readCaller, readMutationCaller, unavailable } from "../../threadAccess.ts";
10import { ProjectToolkit } from "./tools.ts";
11​
12function projectFailure(error: Project.ProjectServiceError) {
13 if (error._tag === "ProjectOperationError") return unavailable();
14 const message =
15 error._tag === "ProjectNotFoundError"
16 ? "The project was not found."
17 : error._tag === "ProjectConflictError"
18 ? "The workspace is already registered to a project."
19 : "The project is not empty; force=true is required to delete it.";
20 return new OrchestratorMcpFailure({ code: "invalid_request", message });
22​
23const access = Effect.gen(function* () {
24 yield* readCaller();
25 return yield* Project.ProjectService;
26});
27const mutation = Effect.gen(function* () {
28 const { caller } = yield* readMutationCaller();
29 if (
30 caller.archivedAt !== null ||
31 caller.runtimeMode !== "full-access" ||
32 caller.interactionMode !== "default"
33 )
34 return yield* new OrchestratorMcpFailure({
35 code: "capability_denied",
36 message: "Project changes require a live full-access/default calling thread.",
37 });
38 return yield* Project.ProjectService;
39});
40export const ProjectHandlersLive = ProjectToolkit.toLayer({
41 t3_thread_launch: (input) =>
42 Effect.gen(function* () {
43 const { caller, scope } = yield* readMutationCaller();
44 if (caller.runtimeMode !== "full-access" || caller.interactionMode !== "default")
45 return yield* new OrchestratorMcpFailure({
46 code: "capability_denied",
47 message: "Project launches require a full-access/default calling thread.",
48 });
49 const commandId = yield* newCommandId();
50 const threadId = ThreadId.make(commandId);
51 const messageId = MessageId.make(commandId);
52 const attachments = input.attachments ?? [];
53 if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
54 return yield* new OrchestratorMcpFailure({
55 code: "invalid_request",
56 message: "A new thread accepts only pending attachment uploads.",
57 });
58 if (
59 input.scratch === true &&
60 (input.projectId !== undefined || input.workspaceStrategy !== undefined)
61 )
62 return yield* new OrchestratorMcpFailure({
63 code: "invalid_request",
64 message:
65 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",
66 });
67 const projectId =
68 input.scratch === true
69 ? (yield* ManagedProjectFolders.ManagedProjectFolders.pipe(
70 Effect.flatMap((folders) => folders.ensureScratchProject),
71 Effect.mapError(
72 (error) =>
73 new OrchestratorMcpFailure({
74 code: "orchestration_error",
75 message: error.message,
76 }),
77 ),
78 )).projectId
79 : (input.projectId ?? caller.projectId);
80 const result = yield* ThreadMessageIntake.launchThread({
81 commandId,
82 threadId,
83 projectId,
84 title: input.title,
85 modelSelection: input.modelSelection ?? caller.modelSelection,
86 runtimeMode: input.runtimeMode ?? caller.runtimeMode,
87 interactionMode: input.interactionMode ?? caller.interactionMode,
88 workspaceStrategy: input.workspaceStrategy ?? { type: "root" },
89 ...(input.message === undefined && attachments.length === 0
90 ? {}
91 : {
92 initialMessage: {
93 messageId,
94 senderThreadId: scope.threadId,
95 text: input.message ?? "",
96 attachments,
97 },
98 }),
99 createdBy: "agent",
100 creationSource: "mcp",
101 }).pipe(
102 Effect.mapError((error) =>
103 error._tag === "AttachmentClaimError"
104 ? new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message })
105 : unavailable(),
106 ),
107 );
108 const thread = result.projection.thread;
109 const run = result.projection.runs.find((run) => run.userMessageId === messageId);
110 return {
111 threadId: thread.id,
112 projectId: thread.projectId,
113 modelSelection: thread.modelSelection,
114 runId: run?.id ?? null,
115 status: run?.status ?? null,
116 };
117 }),
118 t3_project_list: (input) =>
119 Effect.gen(function* () {
120 const projects = yield* access;
121 const snapshot = yield* projects.snapshot.pipe(Effect.mapError(unavailable));
122 const rows = snapshot.projects.filter((project) => project.deletedAt === null);
123 const start = input.cursor ?? 0,
124 end = start + (input.limit ?? 20);
125 return { projects: rows.slice(start, end), nextCursor: end < rows.length ? end : null };
126 }),
127 t3_project_read: (input) =>
128 Effect.gen(function* () {
129 const projects = yield* access;
130 const result = yield* projects.getById(input.projectId).pipe(Effect.mapError(unavailable));
131 if (Option.isNone(result))
132 return yield* new OrchestratorMcpFailure({
133 code: "invalid_request",
134 message: "The project was not found.",
135 });
136 return result.value;
137 }),
138 t3_project_create: ({ workspaceRoot, ...input }) =>
139 Effect.gen(function* () {
140 const projects = yield* mutation;
141 if (workspaceRoot === undefined) {
142 // Project creation records no model default (only an update does), so
143 // reject what this mode would otherwise drop silently.
144 if (
145 input.scripts !== undefined ||
146 input.createWorkspaceRootIfMissing !== undefined ||
147 input.defaultModelSelection !== undefined
148 )
149 return yield* new OrchestratorMcpFailure({
150 code: "invalid_request",
151 message:
152 "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
153 });
154 const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
155 const created = yield* folders
156 .createNamedProject({ name: input.title })
157 .pipe(
158 Effect.mapError(
159 (error) =>
160 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
161 ),
162 );
163 const project = yield* projects
164 .getById(created.projectId)
165 .pipe(
166 Effect.mapError(unavailable),
167 Effect.flatMap(
168 Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
169 ),
170 );
171 return {
172 ...project,
173 ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
174 };
175 }
176 const commandId = yield* newCommandId();
177 return yield* projects
178 .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
179 .pipe(Effect.mapError(projectFailure));
180 }),
181 t3_project_update: (input) =>
182 Effect.gen(function* () {
183 const projects = yield* mutation;
184 return yield* projects
185 .update({ ...input, commandId: yield* newCommandId() })
186 .pipe(Effect.mapError(projectFailure));
187 }),
188 t3_project_delete: (input) =>
189 Effect.gen(function* () {
190 const projects = yield* mutation;
191 return yield* projects
192 .delete({ ...input, commandId: yield* newCommandId() })
193 .pipe(Effect.mapError(projectFailure));
194 }),
195 t3_project_clone: (input) =>
196 Effect.gen(function* () {
197 yield* mutation;
198 const repositories = yield* Repositories.SourceControlRepositoryService;
199 return yield* repositories.cloneRepository(input).pipe(
200 Effect.mapError(
201 (error) =>
202 new OrchestratorMcpFailure({
203 code: "orchestration_error",
204 message: error.detail,
205 }),
206 ),
207 );
208 }),
209});