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