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

ClaudeTextGeneration.ts

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