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