Open History to see the last commit
1/**
2 * ClaudeTextGeneration – Text generation layer using the Claude CLI.
3 *
4 * Implements the same TextGenerationShape contract as CodexTextGeneration but
5 * delegates to the `claude` CLI (`claude -p`) with structured JSON output
6 * instead of the `codex exec` CLI.
7 *
8 * @module ClaudeTextGeneration
9 */
10import { Effect, Layer, Option, Schema, Stream } from "effect";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12
13import { ClaudeModelSelection } from "@t3tools/contracts";
14import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
15
16import { TextGenerationError } from "@t3tools/contracts";
17import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
18import {
19 buildBranchNamePrompt,
20 buildCommitMessagePrompt,
21 buildPrContentPrompt,
22 buildThreadTitlePrompt,
23} from "../Prompts.ts";
24import {
25 normalizeCliError,
26 sanitizeCommitSubject,
27 sanitizePrTitle,
28 sanitizeThreadTitle,
29 toJsonSchemaObject,
30} from "../Utils.ts";
31import {
32 getModelSelectionStringOptionValue,
33 getProviderOptionDescriptors,
34} from "@t3tools/shared/model";
35import {
36 getClaudeModelCapabilities,
37 normalizeClaudeCliEffort,
38 resolveClaudeApiModelId,
39 resolveClaudeEffort,
40} from "../../provider/Layers/ClaudeProvider.ts";
41import { ServerSettingsService } from "../../serverSettings.ts";
42
43const CLAUDE_TIMEOUT_MS = 180_000;
44
45/**
46 * Schema for the wrapper JSON returned by `claude -p --output-format json`.
47 * We only care about `structured_output`.
48 */
49const ClaudeOutputEnvelope = Schema.Struct({
50 structured_output: Schema.Unknown,
51});
52
53const makeClaudeTextGeneration = Effect.gen(function* () {
54 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
55 const serverSettingsService = yield* Effect.service(ServerSettingsService);
56
57 const readStreamAsString = <E>(
58 operation: string,
59 stream: Stream.Stream<Uint8Array, E>,
60 ): Effect.Effect<string, TextGenerationError> =>
61 stream.pipe(
62 Stream.decodeText(),
63 Stream.runFold(
64 () => "",
65 (acc, chunk) => acc + chunk,
66 ),
67 Effect.mapError((cause) =>
68 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
69 ),
70 );
71
72 /**
73 * Spawn the Claude CLI with structured JSON output and return the parsed,
74 * schema-validated result.
75 */
76 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
77 operation,
78 cwd,
79 prompt,
80 outputSchemaJson,
81 modelSelection,
82 }: {
83 operation:
84 | "generateCommitMessage"
85 | "generatePrContent"
86 | "generateBranchName"
87 | "generateThreadTitle";
88 cwd: string;
89 prompt: string;
90 outputSchemaJson: S;
91 modelSelection: ClaudeModelSelection;
92 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
93 const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
94 const caps = getClaudeModelCapabilities(modelSelection.model);
95 const descriptors = getProviderOptionDescriptors({
96 caps,
97 selections: modelSelection.options,
98 });
99 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
100 const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort");
101 const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);
102 const cliEffort = normalizeClaudeCliEffort(resolvedEffort);
103 const thinkingDescriptor = findDescriptor("thinking");
104 const fastModeDescriptor = findDescriptor("fastMode");
105 const thinking =
106 thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
107 const fastMode =
108 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
109 const settings = {
110 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
111 ...(fastMode ? { fastMode: true } : {}),
112 };
113
114 const claudeSettings = yield* Effect.map(
115 serverSettingsService.getSettings,
116 (settings) => settings.providers.claudeAgent,
117 ).pipe(Effect.catch(() => Effect.undefined));
118
119 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
120 const command = ChildProcess.make(
121 claudeSettings?.binaryPath || "claude",
122 [
123 "-p",
124 "--output-format",
125 "json",
126 "--json-schema",
127 jsonSchemaStr,
128 "--model",
129 resolveClaudeApiModelId(modelSelection),
130 ...(cliEffort ? ["--effort", cliEffort] : []),
131 ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
132 "--dangerously-skip-permissions",
133 ],
134 {
135 cwd,
136 shell: process.platform === "win32",
137 stdin: {
138 stream: Stream.encodeText(Stream.make(prompt)),
139 },
140 },
141 );
142
143 const child = yield* commandSpawner
144 .spawn(command)
145 .pipe(
146 Effect.mapError((cause) =>
147 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
148 ),
149 );
150
151 const [stdout, stderr, exitCode] = yield* Effect.all(
152 [
153 readStreamAsString(operation, child.stdout),
154 readStreamAsString(operation, child.stderr),
155 child.exitCode.pipe(
156 Effect.mapError((cause) =>
157 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
158 ),
159 ),
160 ],
161 { concurrency: "unbounded" },
162 );
163
164 if (exitCode !== 0) {
165 const stderrDetail = stderr.trim();
166 const stdoutDetail = stdout.trim();
167 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
168 return yield* new TextGenerationError({
169 operation,
170 detail:
171 detail.length > 0
172 ? `Claude CLI command failed: ${detail}`
173 : `Claude CLI command failed with code ${exitCode}.`,
174 });
175 }
176
177 return stdout;
178 });
179
180 const rawStdout = yield* runClaudeCommand().pipe(
181 Effect.scoped,
182 Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
183 Effect.flatMap(
184 Option.match({
185 onNone: () =>
186 Effect.fail(
187 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
188 ),
189 onSome: (value) => Effect.succeed(value),
190 }),
191 ),
192 );
193
194 const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
195 rawStdout,
196 ).pipe(
197 Effect.catchTag("SchemaError", (cause) =>
198 Effect.fail(
199 new TextGenerationError({
200 operation,
201 detail: "Claude CLI returned unexpected output format.",
202 cause,
203 }),
204 ),
205 ),
206 );
207
208 return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
209 Effect.catchTag("SchemaError", (cause) =>
210 Effect.fail(
211 new TextGenerationError({
212 operation,
213 detail: "Claude returned invalid structured output.",
214 cause,
215 }),
216 ),
217 ),
218 );
219 });
220
221 // ---------------------------------------------------------------------------
222 // TextGenerationShape methods
223 // ---------------------------------------------------------------------------
224
225 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
226 "ClaudeTextGeneration.generateCommitMessage",
227 )(function* (input) {
228 const { prompt, outputSchema } = buildCommitMessagePrompt({
229 branch: input.branch,
230 stagedSummary: input.stagedSummary,
231 stagedPatch: input.stagedPatch,
232 includeBranch: input.includeBranch === true,
233 });
234
235 if (input.modelSelection.provider !== "claudeAgent") {
236 return yield* new TextGenerationError({
237 operation: "generateCommitMessage",
238 detail: "Invalid model selection.",
239 });
240 }
241
242 const generated = yield* runClaudeJson({
243 operation: "generateCommitMessage",
244 cwd: input.cwd,
245 prompt,
246 outputSchemaJson: outputSchema,
247 modelSelection: input.modelSelection,
248 });
249
250 return {
251 subject: sanitizeCommitSubject(generated.subject),
252 body: generated.body.trim(),
253 ...("branch" in generated && typeof generated.branch === "string"
254 ? { branch: sanitizeFeatureBranchName(generated.branch) }
255 : {}),
256 };
257 });
258
259 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
260 "ClaudeTextGeneration.generatePrContent",
261 )(function* (input) {
262 const { prompt, outputSchema } = buildPrContentPrompt({
263 baseBranch: input.baseBranch,
264 headBranch: input.headBranch,
265 commitSummary: input.commitSummary,
266 diffSummary: input.diffSummary,
267 diffPatch: input.diffPatch,
268 });
269
270 if (input.modelSelection.provider !== "claudeAgent") {
271 return yield* new TextGenerationError({
272 operation: "generatePrContent",
273 detail: "Invalid model selection.",
274 });
275 }
276
277 const generated = yield* runClaudeJson({
278 operation: "generatePrContent",
279 cwd: input.cwd,
280 prompt,
281 outputSchemaJson: outputSchema,
282 modelSelection: input.modelSelection,
283 });
284
285 return {
286 title: sanitizePrTitle(generated.title),
287 body: generated.body.trim(),
288 };
289 });
290
291 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
292 "ClaudeTextGeneration.generateBranchName",
293 )(function* (input) {
294 const { prompt, outputSchema } = buildBranchNamePrompt({
295 message: input.message,
296 attachments: input.attachments,
297 });
298
299 if (input.modelSelection.provider !== "claudeAgent") {
300 return yield* new TextGenerationError({
301 operation: "generateBranchName",
302 detail: "Invalid model selection.",
303 });
304 }
305
306 const generated = yield* runClaudeJson({
307 operation: "generateBranchName",
308 cwd: input.cwd,
309 prompt,
310 outputSchemaJson: outputSchema,
311 modelSelection: input.modelSelection,
312 });
313
314 return {
315 branch: sanitizeBranchFragment(generated.branch),
316 };
317 });
318
319 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
320 "ClaudeTextGeneration.generateThreadTitle",
321 )(function* (input) {
322 const { prompt, outputSchema } = buildThreadTitlePrompt({
323 message: input.message,
324 attachments: input.attachments,
325 });
326
327 if (input.modelSelection.provider !== "claudeAgent") {
328 return yield* new TextGenerationError({
329 operation: "generateThreadTitle",
330 detail: "Invalid model selection.",
331 });
332 }
333
334 const generated = yield* runClaudeJson({
335 operation: "generateThreadTitle",
336 cwd: input.cwd,
337 prompt,
338 outputSchemaJson: outputSchema,
339 modelSelection: input.modelSelection,
340 });
341
342 return {
343 title: sanitizeThreadTitle(generated.title),
344 };
345 });
346
347 return {
348 generateCommitMessage,
349 generatePrContent,
350 generateBranchName,
351 generateThreadTitle,
352 } satisfies TextGenerationShape;
353});
354
355export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);