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

ClaudeTextGeneration.ts

361 lines11.1 KB

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