Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import type { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
5import {
6 isProviderAvailable,
7 isProviderTextGenerationCapable,
8 resolveProjectProviderInstanceEnabled,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits";
12import {
13 defaultTextGenerationModel,
14 fallbackTextGenerationModelSelection,
15} from "@t3tools/shared/serverSettings";
16import * as ServerSettings from "../serverSettings.ts";
17import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
18import { TextGenerationError } from "@t3tools/contracts";
19
20import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
21import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
22import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
23import * as ThreadTitleLinks from "./ThreadTitleLinks.ts";
24import * as TextGenerators from "./TextGenerators.ts";
25import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
26
27export type {
28 BranchNameGenerationInput,
29 BranchNameGenerationResult,
30 CommitMessageGenerationInput,
31 CommitMessageGenerationResult,
32 PrContentGenerationInput,
33 PrContentGenerationResult,
34 ReviewGuideGenerationInput,
35 ReviewGuideGenerationResult,
36 ThreadTitleGenerationInput,
37 ThreadTitleGenerationResult,
38 TranscriptionPostProcessingInput,
39 TranscriptionPostProcessingResult,
40} from "@t3tools/provider-core/server/textGeneration";
41
42export class TextGeneration extends Context.Service<TextGeneration, ProviderTextGeneration>()(
43 "t3/textGeneration/TextGeneration",
44) {}
45
46type TextGenerationOp =
47 | "generateCommitMessage"
48 | "generatePrContent"
49 | "generateBranchName"
50 | "generateThreadTitle"
51 | "generateReviewGuide"
52 | "generateTranscriptionPostProcessing";
53
54const resolveInstance = (
55 registry: ProviderInstanceRegistry.ProviderInstanceRegistry["Service"],
56 operation: TextGenerationOp,
57 instanceId: ProviderInstanceId,
58): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
59 registry.getInstance(instanceId).pipe(
60 Effect.flatMap((instance) =>
61 instance
62 ? Effect.succeed(instance.textGeneration)
63 : Effect.fail(
64 new TextGenerationError({
65 operation,
66 detail: `No provider instance registered for id '${instanceId}'.`,
67 }),
68 ),
69 ),
70 );
71
72// Review guides investigate the checkout read-only; the other drivers reject that request.
73const INVESTIGATING_DRIVERS = new Set(["codex", "claudeAgent"]);
74
75/** @public */
76export const make = Effect.gen(function* () {
77 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
78 const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
79 const serverSettings = yield* ServerSettings.ServerSettingsService;
80 const textGenerators = yield* TextGenerators.TextGenerators;
81 const generate = Effect.fn("TextGeneration.generate")(function* <A>(
82 operation: TextGenerationOp,
83 selection: ModelSelection,
84 invoke: (
85 service: ProviderTextGeneration,
86 modelSelection: ModelSelection,
87 ) => Effect.Effect<A, TextGenerationError>,
88 ) {
89 const textGenerator = yield* textGenerators.runner(selection.instanceId);
90 // A review guide reaches a text generator only through a fallback; it needs an agent instead.
91 const textGeneratorId = selection.instanceId;
92 const textGeneratorCannotRun =
93 textGenerator !== undefined && operation === "generateReviewGuide";
94 if (textGenerator !== undefined && !textGeneratorCannotRun) {
95 return yield* invoke(
96 TextGenerationOperations.fromRunner("TextGenerator", textGenerator),
97 selection,
98 );
99 }
100 const snapshots = yield* registry.listInstances.pipe(
101 Effect.flatMap((instances) =>
102 Effect.forEach(instances, (instance) => instance.snapshot.getSnapshot),
103 ),
104 );
105 const now = DateTime.toEpochMillis(yield* DateTime.now);
106 const selected = snapshots.find((provider) => provider.instanceId === selection.instanceId);
107 // Only a failed probe counts: a pending one is also not installed yet.
108 const unusable =
109 textGeneratorCannotRun ||
110 (selected?.enabled === true &&
111 selected.status === "error" &&
112 (!selected.installed || selected.auth.status === "unauthenticated"));
113 if (unusable || exhaustedUsageWindow(selected, now, selection.model)) {
114 const settings = yield* serverSettings.getSettings.pipe(
115 Effect.mapError(
116 (cause) =>
117 new TextGenerationError({
118 operation,
119 detail: "Could not read fallback model settings.",
120 cause,
121 }),
122 ),
123 );
124 selection =
125 fallbackTextGenerationModelSelection(
126 settings.providerInstances,
127 (instanceId, driver) => {
128 const provider = snapshots.find((candidate) => candidate.instanceId === instanceId);
129 return (
130 instanceId !== selection.instanceId &&
131 provider?.enabled === true &&
132 resolveProjectProviderInstanceEnabled(settings, null, instanceId) &&
133 provider.installed &&
134 provider.auth.status !== "unauthenticated" &&
135 provider.status !== "error" &&
136 isProviderAvailable(provider) &&
137 isProviderTextGenerationCapable(provider) &&
138 (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) &&
139 !exhaustedUsageWindow(provider, now, defaultTextGenerationModel(driver))
140 );
141 },
142 { includeConfiguredInstances: true },
143 ) ?? selection;
144 }
145 if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) {
146 return yield* new TextGenerationError({
147 operation,
148 detail:
149 "Review guides need a coding agent that can read the checkout. None is ready. Pick Codex or Claude as the review guide model in Settings → Source control.",
150 });
151 }
152 return yield* resolveInstance(registry, operation, selection.instanceId).pipe(
153 Effect.flatMap((service) => invoke(service, selection)),
154 );
155 });
156 return TextGeneration.of({
157 generateCommitMessage: Effect.fn("TextGeneration.generateCommitMessage")(function (input) {
158 return generate("generateCommitMessage", input.modelSelection, (service, modelSelection) =>
159 service.generateCommitMessage({ ...input, modelSelection }),
160 );
161 }),
162 generatePrContent: Effect.fn("TextGeneration.generatePrContent")(function (input) {
163 return generate("generatePrContent", input.modelSelection, (service, modelSelection) =>
164 service.generatePrContent({ ...input, modelSelection }),
165 );
166 }),
167 generateBranchName: Effect.fn("TextGeneration.generateBranchName")(function (input) {
168 return generate("generateBranchName", input.modelSelection, (service, modelSelection) =>
169 service.generateBranchName({ ...input, modelSelection }),
170 );
171 }),
172 generateReviewGuide: Effect.fn("TextGeneration.generateReviewGuide")(function (input) {
173 return generate("generateReviewGuide", input.modelSelection, (service, modelSelection) =>
174 service.generateReviewGuide({ ...input, modelSelection }),
175 );
176 }),
177 generateTranscriptionPostProcessing: Effect.fn(
178 "TextGeneration.generateTranscriptionPostProcessing",
179 )(function (input) {
180 return generate(
181 "generateTranscriptionPostProcessing",
182 input.modelSelection,
183 (service, modelSelection) =>
184 service.generateTranscriptionPostProcessing({ ...input, modelSelection }),
185 );
186 }),
187 generateThreadTitle: Effect.fn("TextGeneration.generateThreadTitle")(function (input) {
188 return generate(
189 "generateThreadTitle",
190 input.modelSelection,
191 (textGeneration, modelSelection) =>
192 Effect.gen(function* () {
193 const linkedContext =
194 input.linkedContext ??
195 (yield* ThreadTitleLinks.resolveThreadTitleLinks(input).pipe(
196 Effect.provideService(
197 SourceControlProviderRegistry.SourceControlProviderRegistry,
198 sourceControl,
199 ),
200 ));
201 return yield* textGeneration.generateThreadTitle({
202 ...input,
203 linkedContext,
204 modelSelection,
205 });
206 }),
207 );
208 }),
209 });
210});
211
212export const layer = Layer.effect(TextGeneration, make).pipe(
213 Layer.provideMerge(TextGenerators.layer),
214);