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