Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 type OrchestrationProjectShell,
5 type OrchestrationThreadShell,
6 ThreadId,
7 type ThreadTurnStartBootstrap,
8} from "@t3tools/contracts";
9import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
10import * as Cause from "effect/Cause";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15
16import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
17import * as ThreadBootstrap from "../../../orchestration/Services/ThreadBootstrap.ts";
18import * as McpInvocationContext from "../../McpInvocationContext.ts";
19import {
20 ThreadStartCallerArchivedError,
21 ThreadStartCallerNotFoundError,
22 ThreadStartFailedError,
23 type ThreadStartInput,
24 ThreadStartProjectNotFoundError,
25 type ThreadStartResult,
26 ThreadStartWorktreeBaseRequiredError,
27 ThreadsToolkit,
28} from "./tools.ts";
29
30const TITLE_MAX_CHARS = 80;
31
32export function defaultThreadTitle(prompt: string): string {
33 const firstLine =
34 prompt
35 .split("\n")
36 .find((line) => line.trim().length > 0)
37 ?.trim() ?? prompt;
38 return firstLine.length <= TITLE_MAX_CHARS
39 ? firstLine
40 : `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`;
41}
42
43export function handoffMessageText(
44 caller: Pick<OrchestrationThreadShell, "id" | "title">,
45 prompt: string,
46): string {
47 return `> Handed off from T3 thread "${caller.title}" (${caller.id}).\n\n${prompt}`;
48}
49
50const bytesToHex = (bytes: Uint8Array): string =>
51 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
52
53const uuidFromHex = (hex: string): string =>
54 `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
55
56const make = Effect.gen(function* () {
57 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
58 const bootstrap = yield* ThreadBootstrap.ThreadBootstrap;
59 const crypto = yield* Crypto.Crypto;
60
61 const randomUUID = crypto.randomUUIDv4.pipe(Effect.orDie);
62 const randomHex = (byteLength: number) =>
63 crypto.randomBytes(byteLength).pipe(Effect.map(bytesToHex), Effect.orDie);
64 const deterministicUUID = (seed: string) =>
65 crypto
66 .digest("SHA-256", new TextEncoder().encode(seed))
67 .pipe(Effect.map(bytesToHex), Effect.map(uuidFromHex), Effect.orDie);
68
69 const readThread = (threadId: ThreadId) =>
70 snapshots
71 .getThreadShellById(threadId)
72 .pipe(Effect.mapError((cause) => new ThreadStartFailedError({ cause })));
73
74 const resultOf = (
75 thread: Pick<
76 OrchestrationThreadShell,
77 | "id"
78 | "title"
79 | "modelSelection"
80 | "runtimeMode"
81 | "interactionMode"
82 | "branch"
83 | "worktreePath"
84 >,
85 alreadyStarted: boolean,
86 ): ThreadStartResult => ({
87 threadId: thread.id,
88 title: thread.title,
89 modelSelection: thread.modelSelection,
90 runtimeMode: thread.runtimeMode,
91 interactionMode: thread.interactionMode,
92 branch: thread.branch,
93 worktreePath: thread.worktreePath,
94 alreadyStarted,
95 });
96
97 const worktreeBootstrap = Effect.fn("ThreadsToolkit.worktreeBootstrap")(function* (
98 input: NonNullable<ThreadStartInput["worktree"]>,
99 caller: OrchestrationThreadShell,
100 project: OrchestrationProjectShell,
101 ) {
102 const baseBranch = input.baseBranch ?? caller.branch;
103 if (baseBranch === null) {
104 return yield* new ThreadStartWorktreeBaseRequiredError({});
105 }
106 const hex = yield* randomHex(4);
107 const branch = input.branch ?? buildTemporaryWorktreeBranchName(() => hex);
108 return {
109 projectCwd: project.workspaceRoot,
110 baseBranch,
111 branch,
112 ...(input.startFromOrigin === true ? { startFromOrigin: true } : {}),
113 } satisfies NonNullable<ThreadTurnStartBootstrap["prepareWorktree"]>;
114 });
115
116 const start = Effect.fn("ThreadsToolkit.t3_thread_start")(function* (input: ThreadStartInput) {
117 const scope = yield* McpInvocationContext.requireMcpCapability("threads");
118 const caller = yield* readThread(scope.threadId);
119 if (Option.isNone(caller)) {
120 return yield* new ThreadStartCallerNotFoundError({ threadId: scope.threadId });
121 }
122 if (caller.value.archivedAt !== null) {
123 return yield* new ThreadStartCallerArchivedError({ threadId: scope.threadId });
124 }
125 const project = yield* snapshots
126 .getProjectShellById(caller.value.projectId)
127 .pipe(Effect.mapError((cause) => new ThreadStartFailedError({ cause })));
128 if (Option.isNone(project)) {
129 return yield* new ThreadStartProjectNotFoundError({ projectId: caller.value.projectId });
130 }
131
132 const requestKey = input.clientRequestId;
133 const threadId = ThreadId.make(
134 requestKey === undefined
135 ? yield* randomUUID
136 : yield* deterministicUUID(`${scope.threadId}\n${requestKey}`),
137 );
138 if (requestKey !== undefined) {
139 const existing = yield* readThread(threadId);
140 if (Option.isSome(existing)) {
141 return resultOf(existing.value, true);
142 }
143 }
144 const commandId = CommandId.make(
145 `server:mcp-thread-start:${scope.threadId}:${requestKey ?? (yield* randomUUID)}`,
146 );
147 const messageId = MessageId.make(yield* randomUUID);
148
149 const modelSelection = input.modelSelection ?? caller.value.modelSelection;
150 const interactionMode = input.interactionMode ?? caller.value.interactionMode;
151 const runtimeMode = caller.value.runtimeMode;
152 const titleSeed = defaultThreadTitle(input.prompt);
153 const title = input.title ?? titleSeed;
154 const createdAt = DateTime.formatIso(yield* DateTime.now);
155
156 const prepareWorktree = input.worktree
157 ? yield* worktreeBootstrap(input.worktree, caller.value, project.value)
158 : undefined;
159 const createThread = {
160 projectId: caller.value.projectId,
161 title,
162 modelSelection,
163 runtimeMode,
164 interactionMode,
165 branch: prepareWorktree ? null : caller.value.branch,
166 worktreePath: prepareWorktree ? null : caller.value.worktreePath,
167 createdAt,
168 };
169
170 const alreadyStarted = yield* bootstrap
171 .dispatchTurnStart({
172 type: "thread.turn.start",
173 commandId,
174 threadId,
175 message: {
176 messageId,
177 role: "user",
178 text: handoffMessageText(caller.value, input.prompt),
179 attachments: [],
180 },
181 modelSelection,
182 ...(input.title === undefined ? { titleSeed } : {}),
183 runtimeMode,
184 interactionMode,
185 bootstrap: {
186 createThread,
187 ...(prepareWorktree ? { prepareWorktree, runSetupScript: true } : {}),
188 },
189 createdAt,
190 })
191 .pipe(
192 Effect.catchCause((cause) =>
193 Cause.hasInterruptsOnly(cause)
194 ? Effect.failCause(cause as Cause.Cause<never>)
195 : Effect.fail(new ThreadStartFailedError({ cause })),
196 ),
197 Effect.as(false),
198 requestKey === undefined
199 ? (effect) => effect
200 : Effect.catchTag("ThreadStartFailedError", (error) =>
201 readThread(threadId).pipe(
202 Effect.flatMap((thread) =>
203 Option.isSome(thread) ? Effect.succeed(true) : Effect.fail(error),
204 ),
205 ),
206 ),
207 );
208
209 const started = yield* readThread(threadId);
210 return Option.isSome(started)
211 ? resultOf(started.value, alreadyStarted)
212 : resultOf({ id: threadId, ...createThread }, false);
213 });
214
215 return ThreadsToolkit.of({ t3_thread_start: start });
216});
217
218export const ThreadsToolkitHandlersLive = ThreadsToolkit.toLayer(make);