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

ClaudeTextGeneration.ts

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