Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeTextGeneration.ts

420 lines13.8 KB

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/process";
16​
17import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
18import { formatGeneratedBranchName, 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 "--permission-mode",
218 "dontAsk",
219 ],
220 { env: claudeEnvironment },
221 );
222 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
223 env: claudeEnvironment,
224 cwd: workingDirectory,
225 shell: spawnCommand.shell,
226 stdin: {
227 stream: Stream.encodeText(Stream.make(prompt)),
228 },
229 });
230​
231 const child = yield* commandSpawner
232 .spawn(command)
233 .pipe(
234 Effect.mapError((cause) =>
235 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
236 ),
237 );
238​
239 const [stdout, stderr, exitCode] = yield* Effect.all(
240 [
241 readStreamAsString(operation, child.stdout),
242 readStreamAsString(operation, child.stderr),
243 child.exitCode.pipe(
244 Effect.mapError((cause) =>
245 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
246 ),
247 ),
248 ],
249 { concurrency: "unbounded" },
250 );
251​
252 if (exitCode !== 0) {
253 const stderrDetail = stderr.trim();
254 const stdoutDetail = stdout.trim();
255 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
256 return yield* new TextGenerationError({
257 operation,
258 detail:
259 detail.length > 0
260 ? `Claude CLI command failed: ${detail}`
261 : `Claude CLI command failed with code ${exitCode}.`,
262 });
263 }
264​
265 return stdout;
266 });
267​
268 const rawStdout = yield* runClaudeCommand().pipe(
269 Effect.scoped,
270 Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
271 Effect.flatMap(
272 Option.match({
273 onNone: () =>
274 Effect.fail(
275 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
276 ),
277 onSome: (value) => Effect.succeed(value),
278 }),
279 ),
280 );
281​
282 const output = yield* decodeClaudeOutput(rawStdout).pipe(
283 Effect.catchTags({
284 SchemaError: (cause) =>
285 Effect.fail(
286 new TextGenerationError({
287 operation,
288 detail: "Claude CLI returned unexpected output format.",
289 cause,
290 }),
291 ),
292 }),
293 );
294 const envelope = isClaudeOutputEnvelope(output)
295 ? output
296 : output.findLast((message) => message.type === "result");
297​
298 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
299 return yield* decodeOutput(envelope?.structured_output).pipe(
300 Effect.catchTags({
301 SchemaError: (cause) =>
302 Effect.fail(
303 new TextGenerationError({
304 operation,
305 detail: "Claude returned invalid structured output.",
306 cause,
307 }),
308 ),
309 }),
310 );
311 });
312​
313 // ---------------------------------------------------------------------------
314 // TextGeneration service methods
315 // ---------------------------------------------------------------------------
316​
317 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
318 Effect.fn("ClaudeTextGeneration.generateCommitMessage")(function* (input) {
319 const { prompt, outputSchema } = buildCommitMessagePrompt({
320 branch: input.branch,
321 stagedSummary: input.stagedSummary,
322 stagedPatch: input.stagedPatch,
323 includeBranch: input.includeBranch === true,
324 policy: input.policy,
325 });
326​
327 const generated = yield* runClaudeJson({
328 operation: "generateCommitMessage",
329 cwd: input.cwd,
330 prompt,
331 outputSchemaJson: outputSchema,
332 modelSelection: input.modelSelection,
333 });
334​
335 return {
336 subject: sanitizeCommitSubject(generated.subject),
337 body: generated.body.trim(),
338 ...("branch" in generated && typeof generated.branch === "string"
339 ? { branch: sanitizeFeatureBranchName(generated.branch) }
340 : {}),
341 };
342 });
343​
344 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
345 Effect.fn("ClaudeTextGeneration.generatePrContent")(function* (input) {
346 const { prompt, outputSchema } = buildPrContentPrompt({
347 baseBranch: input.baseBranch,
348 headBranch: input.headBranch,
349 commitSummary: input.commitSummary,
350 diffSummary: input.diffSummary,
351 diffPatch: input.diffPatch,
352 policy: input.policy,
353 changeRequestTemplate: input.changeRequestTemplate,
354 });
355​
356 const generated = yield* runClaudeJson({
357 operation: "generatePrContent",
358 cwd: input.cwd,
359 prompt,
360 outputSchemaJson: outputSchema,
361 modelSelection: input.modelSelection,
362 });
363​
364 return {
365 title: sanitizePrTitle(generated.title),
366 body: generated.body.trim(),
367 };
368 });
369​
370 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
371 Effect.fn("ClaudeTextGeneration.generateBranchName")(function* (input) {
372 const { prompt, outputSchema } = buildBranchNamePrompt({
373 message: input.message,
374 attachments: input.attachments,
375 naming: input.naming,
376 });
377​
378 const generated = yield* runClaudeJson({
379 operation: "generateBranchName",
380 cwd: input.cwd,
381 prompt,
382 outputSchemaJson: outputSchema,
383 modelSelection: input.modelSelection,
384 });
385​
386 return {
387 branch: formatGeneratedBranchName(generated.branch, input.naming),
388 };
389 });
390​
391 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
392 Effect.fn("ClaudeTextGeneration.generateThreadTitle")(function* (input) {
393 const { prompt, outputSchema } = buildThreadTitlePrompt({
394 message: input.message,
395 previousTitle: input.previousTitle,
396 linkedContext: input.linkedContext,
397 attachments: input.attachments,
398 });
399​
400 const generated = yield* runClaudeJson({
401 operation: "generateThreadTitle",
402 cwd: input.cwd,
403 prompt,
404 outputSchemaJson: outputSchema,
405 modelSelection: input.modelSelection,
406 });
407​
408 return {
409 title: sanitizeThreadTitle(generated.title),
410 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
411 };
412 });
413​
414 return {
415 generateCommitMessage,
416 generatePrContent,
417 generateBranchName,
418 generateThreadTitle,
419 } satisfies TextGeneration.TextGeneration["Service"];
420});