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

MuseTextGeneration.ts

350 lines13.5 KB

1import {
2 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
3 MUSE_DEFAULT_MODEL,
4 type ModelSelection,
5 type MuseSettings,
6 type ServerProviderModel,
7 TextGenerationError,
8} from "@t3tools/contracts";
9import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
10import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
11import { extractJsonObject } from "@t3tools/shared/schemaJson";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16​
17import {
18 createMuseSdkHost,
19 createMuseSdkHostEffect,
20 type MuseSdkHost,
21} from "../provider/museSdk.ts";
22import { museModelCapabilities, resolveMuseReasoningEffort } from "../provider/museModelCatalog.ts";
23import type * as TextGeneration from "./TextGeneration.ts";
24import {
25 buildBranchNamePrompt,
26 buildCommitMessagePrompt,
27 buildPrContentPrompt,
28 buildThreadTitlePrompt,
29} from "./TextGenerationPrompts.ts";
30import {
31 sanitizeCommitSubject,
32 sanitizePrTitle,
33 sanitizeThreadTitle,
34 toJsonSchemaObject,
35} from "./TextGenerationUtils.ts";
36​
37const SessionStarted = Schema.Struct({ session: Schema.Struct({ sessionId: Schema.String }) });
38const ItemNotification = Schema.Struct({
39 sessionId: Schema.String,
40 item: Schema.Struct({
41 itemId: Schema.String,
42 kind: Schema.String,
43 revision: Schema.Int,
44 turnId: Schema.optionalKey(Schema.String),
45 text: Schema.optionalKey(Schema.String),
46 retracted: Schema.optionalKey(Schema.Boolean),
47 truncated: Schema.optionalKey(Schema.Boolean),
48 }),
49});
50const TurnCompleted = Schema.Struct({
51 sessionId: Schema.String,
52 turnId: Schema.String,
53 terminal: Schema.String,
54 error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),
55});
56const ApprovalRequested = Schema.Struct({
57 sessionId: Schema.String,
58 approvalId: Schema.String,
59 currentRequirementId: Schema.Unknown,
60 availableChoices: Schema.Array(
61 Schema.Struct({ choiceId: Schema.String, decision: Schema.String }),
62 ),
63});
64const UserInputRequested = Schema.Struct({
65 sessionId: Schema.String,
66 userInputId: Schema.String,
67});
68const decodeSession = Schema.decodeUnknownSync(SessionStarted);
69const decodeItem = Schema.decodeUnknownSync(ItemNotification);
70const decodeCompleted = Schema.decodeUnknownSync(TurnCompleted);
71const decodeApproval = Schema.decodeUnknownSync(ApprovalRequested);
72const decodeUserInput = Schema.decodeUnknownSync(UserInputRequested);
73const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
74const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
75​
76type Operation = keyof TextGeneration.TextGeneration["Service"];
77​
78async function generateMuseText(
79 host: MuseSdkHost,
80 workspaceRoot: string,
81 prompt: string,
82 modelId: string | undefined,
83 reasoningEffort: string | undefined,
84 signal: AbortSignal,
85) {
86 let sessionId: string | undefined;
87 const turnId = host.connection.mintCommandId();
88 const messages = new Map<string, (typeof ItemNotification.Type)["item"]>();
89 let resolveCompletion: (text: string) => void = () => {};
90 let rejectCompletion: (error: unknown) => void = () => {};
91 const completion = new Promise<string>((resolve, reject) => {
92 resolveCompletion = resolve;
93 rejectCompletion = reject;
94 });
95 // Notifications may settle the turn before the turn/start acknowledgement arrives.
96 void completion.catch(() => {});
97 const rejectInteractive = async (method: string, params: Record<string, unknown>) => {
98 if (method === "approval/requested") {
99 const approval = decodeApproval(params);
100 if (approval.sessionId !== sessionId) return;
101 rejectCompletion(new Error("Muse requested an interactive action during text generation."));
102 const deny = approval.availableChoices.find((choice) => choice.decision === "denied");
103 if (deny) {
104 await host.connection.command("approval/decide", {
105 sessionId,
106 approvalId: approval.approvalId,
107 requirementId: approval.currentRequirementId,
108 choiceId: deny.choiceId,
109 });
110 }
111 } else {
112 const request = decodeUserInput(params);
113 if (request.sessionId !== sessionId) return;
114 rejectCompletion(new Error("Muse requested an interactive action during text generation."));
115 await host.connection.command("userInput/cancel", {
116 sessionId,
117 userInputId: request.userInputId,
118 reason: "T3 Code text generation cannot request user input.",
119 });
120 }
121 };
122 host.connection.onNotification((notification) => {
123 try {
124 if (notification.method === "item/completed" || notification.method === "item/updated") {
125 const { item, sessionId: itemSessionId } = decodeItem(notification.params);
126 if (itemSessionId !== sessionId || item.turnId !== turnId || item.kind !== "agentMessage")
127 return;
128 const previous = messages.get(item.itemId);
129 if (!previous || item.revision > previous.revision) messages.set(item.itemId, item);
130 } else if (notification.method === "turn/completed") {
131 const completed = decodeCompleted(notification.params);
132 if (completed.sessionId !== sessionId || completed.turnId !== turnId) return;
133 if (completed.terminal === "completed") {
134 // A turn may include commentary before its final structured answer.
135 const answer = [...messages.values()].findLast((item) => !item.retracted);
136 if (answer?.truncated) {
137 rejectCompletion(new Error("Muse text generation returned a truncated response."));
138 } else {
139 resolveCompletion(answer?.text ?? "");
140 }
141 } else {
142 rejectCompletion(
143 new Error(completed.error?.message ?? `Muse turn ${completed.terminal}.`),
144 );
145 }
146 } else if (
147 notification.method === "approval/requested" ||
148 notification.method === "userInput/requested"
149 ) {
150 void rejectInteractive(notification.method, notification.params ?? {}).catch(
151 rejectCompletion,
152 );
153 } else if (notification.method === "view/gap") {
154 rejectCompletion(new Error("Muse text generation lost part of its response."));
155 }
156 } catch (error) {
157 rejectCompletion(error);
158 }
159 });
160 host.connection.onProtocolError(rejectCompletion);
161 host.connection.onServerRequest(async () => {
162 const error = new Error("T3 Code text generation cannot approve interactive requests.");
163 rejectCompletion(error);
164 throw error;
165 });
166 void host.connection.closed.then(() => {
167 rejectCompletion(new Error("Muse connection closed before text generation completed."));
168 });
169 void host.exited.then(() => {
170 rejectCompletion(new Error("Muse exited before text generation completed."));
171 });
172 const onAbort = () => rejectCompletion(signal.reason);
173 signal.addEventListener("abort", onAbort, { once: true });
174 try {
175 signal.throwIfAborted();
176 const started = decodeSession(
177 await host.connection.command("session/start", {
178 workspaceRoot,
179 providerId: "meta",
180 ...(modelId ? { modelId } : {}),
181 approvalMode: "denyUnmatched",
182 }),
183 );
184 sessionId = started.session.sessionId;
185 const acknowledged = host.connection.command(
186 "turn/start",
187 {
188 sessionId,
189 input: [{ type: "text", text: prompt }],
190 ...(reasoningEffort !== undefined ? { reasoningEffort } : {}),
191 },
192 { commandId: turnId },
193 );
194 return await Promise.race([acknowledged.then(() => completion), completion]);
195 } finally {
196 signal.removeEventListener("abort", onAbort);
197 }
199​
200export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(function* (
201 settings: MuseSettings,
202 options: {
203 readonly environment?: NodeJS.ProcessEnv;
204 readonly modelCatalog?: Effect.Effect<ReadonlyArray<ServerProviderModel>>;
205 /** Test hook. */
206 readonly createHost?: typeof createMuseSdkHost;
207 } = {},
208) {
209 const { environment, modelCatalog = Effect.succeed([]), createHost } = options;
210 const fileSystem = yield* FileSystem.FileSystem;
211 const runMuseJson = Effect.fn("runMuseJson")(function* <S extends Schema.Top>(input: {
212 operation: Operation;
213 prompt: string;
214 outputSchema: S;
215 modelSelection: ModelSelection;
216 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
217 const { operation } = input;
218 if (!settings.enabled) {
219 return yield* new TextGenerationError({ operation, detail: "Muse Code is disabled." });
220 }
221 const selectedModel = input.modelSelection.model.trim();
222 const models = yield* modelCatalog;
223 // "default" is the catalog's default model, as in chat. Without one, Muse picks.
224 const catalogModel =
225 selectedModel && selectedModel !== MUSE_DEFAULT_MODEL
226 ? models.find((model) => model.slug === selectedModel)
227 : models.find((model) => model.isDefault && !model.isCustom);
228 const modelId =
229 selectedModel && selectedModel !== MUSE_DEFAULT_MODEL ? selectedModel : catalogModel?.slug;
230 const reasoningEffort = resolveMuseReasoningEffort(
231 catalogModel?.capabilities ?? museModelCapabilities(),
232 getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") ??
233 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
234 );
235 const jsonSchema = yield* encodeJson(toJsonSchemaObject(input.outputSchema)).pipe(
236 Effect.mapError(
237 (cause) => new TextGenerationError({ operation, detail: "Invalid output schema.", cause }),
238 ),
239 );
240 const response = yield* Effect.gen(function* () {
241 // Metadata requests already include their context and do not need checkout configuration.
242 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-muse-text-" });
243 const host = yield* Effect.acquireRelease(
244 createMuseSdkHostEffect(
245 {
246 binaryPath: settings.binaryPath,
247 cwd,
248 ...(environment ? { environment } : {}),
249 readOnly: true,
250 // Muse derives SDK turn events from its session log, including completion.
251 sessionLogging: true,
252 },
253 createHost,
254 ),
255 (host: MuseSdkHost) => Effect.promise(() => host.close()),
256 { interruptible: true },
257 );
258 return yield* Effect.tryPromise((signal) =>
259 generateMuseText(
260 host,
261 cwd,
262 `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`,
263 modelId,
264 reasoningEffort,
265 signal,
266 ),
267 );
268 }).pipe(
269 Effect.scoped,
270 Effect.mapError(
271 (cause) =>
272 new TextGenerationError({
273 operation,
274 detail:
275 "Muse Code text generation failed. Check Muse login and availability on this T3 server host.",
276 cause,
277 }),
278 ),
279 Effect.timeoutOption(180_000),
280 Effect.flatMap(
281 Option.match({
282 onNone: () =>
283 Effect.fail(new TextGenerationError({ operation, detail: "Muse request timed out." })),
284 onSome: Effect.succeed,
285 }),
286 ),
287 );
288 const decodeOutput = Schema.decodeEffect(input.outputSchema);
289 return yield* decodeJson(extractJsonObject(response)).pipe(
290 Effect.flatMap(decodeOutput),
291 Effect.mapError(
292 (cause) =>
293 new TextGenerationError({
294 operation,
295 detail: "Muse returned invalid structured output.",
296 cause,
297 }),
298 ),
299 );
300 });
301​
302 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
303 Effect.fn("MuseTextGeneration.generateCommitMessage")(function* (input) {
304 const generated = yield* runMuseJson({
305 operation: "generateCommitMessage",
306 ...buildCommitMessagePrompt({ ...input, includeBranch: input.includeBranch === true }),
307 modelSelection: input.modelSelection,
308 });
309 return {
310 subject: sanitizeCommitSubject(generated.subject),
311 body: generated.body.trim(),
312 ...("branch" in generated && typeof generated.branch === "string"
313 ? { branch: sanitizeFeatureBranchName(generated.branch) }
314 : {}),
315 };
316 });
317 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
318 Effect.fn("MuseTextGeneration.generatePrContent")(function* (input) {
319 const generated = yield* runMuseJson({
320 operation: "generatePrContent",
321 ...buildPrContentPrompt(input),
322 modelSelection: input.modelSelection,
323 });
324 return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
325 });
326 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
327 Effect.fn("MuseTextGeneration.generateBranchName")(function* (input) {
328 const generated = yield* runMuseJson({
329 operation: "generateBranchName",
330 ...buildBranchNamePrompt(input),
331 modelSelection: input.modelSelection,
332 });
333 return { branch: sanitizeBranchFragment(generated.branch) };
334 });
335 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
336 Effect.fn("MuseTextGeneration.generateThreadTitle")(function* (input) {
337 const generated = yield* runMuseJson({
338 operation: "generateThreadTitle",
339 ...buildThreadTitlePrompt(input),
340 modelSelection: input.modelSelection,
341 });
342 return { title: sanitizeThreadTitle(generated.title) };
343 });
344 return {
345 generateCommitMessage,
346 generatePrContent,
347 generateBranchName,
348 generateThreadTitle,
349 } satisfies TextGeneration.TextGeneration["Service"];
350});