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

ClaudeTextGeneration.ts

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