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