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