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

ClaudeTextGeneration.ts

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