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

ClaudeTextGeneration.ts

290 lines9.7 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 FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16​
17import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts";
18import { resolveSpawnCommand } from "@t3tools/shared/shell";
19​
20import * as TextGenerationOperations from "./TextGenerationOperations.ts";
21import { normalizeCliError, toJsonSchemaObject } from "./TextGenerationUtils.ts";
22import {
23 getModelSelectionStringOptionValue,
24 getProviderOptionDescriptors,
25} from "@t3tools/shared/model";
26import {
27 BUNDLED_CLAUDE_MODEL_CATALOG,
28 type ClaudeModelCatalog,
29 getClaudeCatalogModelCapabilities,
30 isClaudeCatalogUltracodeEffort,
31 normalizeClaudeCatalogEffort,
32 resolveClaudeCatalogApiModelId,
33 resolveClaudeCatalogEffort,
34 resolveClaudeModelSlug,
35 scopeClaudeModelCatalog,
36} from "../provider/ClaudeModelCatalog.ts";
37import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
38​
39const CLAUDE_TIMEOUT_MS = 180_000;
40​
41/**
42 * Schema for the wrapper JSON returned by `claude -p --output-format json`.
43 * Verbose mode wraps the result in an array of conversation messages.
44 */
45const ClaudeOutputEnvelope = Schema.Struct({
46 structured_output: Schema.Unknown,
47});
48const ClaudeOutputMessage = Schema.Struct({
49 type: Schema.String,
50 structured_output: Schema.optionalKey(Schema.Unknown),
51});
52const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
53​
54const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
55const decodeClaudeOutput = Schema.decodeEffect(
56 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
57);
58​
59export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
60 claudeSettings: ClaudeSettings,
61 environment?: NodeJS.ProcessEnv,
62 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
63) {
64 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
65 const fileSystem = yield* FileSystem.FileSystem;
66 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
67 const scopedModelCatalog = modelCatalog.pipe(
68 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
69 );
70​
71 const readStreamAsString = <E>(
72 operation: string,
73 stream: Stream.Stream<Uint8Array, E>,
74 ): Effect.Effect<string, TextGenerationError> =>
75 stream.pipe(
76 Stream.decodeText(),
77 Stream.runFold(
78 () => "",
79 (acc, chunk) => acc + chunk,
80 ),
81 Effect.mapError((cause) =>
82 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
83 ),
84 );
85​
86 const encodeJsonForOperation = (
87 operation: TextGenerationOperations.Operation,
88 value: unknown,
89 detail: string,
90 ): Effect.Effect<string, TextGenerationError> =>
91 encodeJsonString(value).pipe(
92 Effect.mapError(
93 (cause) =>
94 new TextGenerationError({
95 operation,
96 detail,
97 cause,
98 }),
99 ),
100 );
101​
102 /**
103 * Spawn the Claude CLI with structured JSON output and return the parsed,
104 * schema-validated result.
105 */
106 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
107 operation,
108 cwd,
109 prompt,
110 outputSchema: outputSchemaJson,
111 modelSelection,
112 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
113 S["Type"],
114 TextGenerationError,
115 S["DecodingServices"]
116 > {
117 const catalog = yield* scopedModelCatalog;
118 const resolvedModelSelection = {
119 ...modelSelection,
120 model: resolveClaudeModelSlug(catalog, modelSelection.model),
121 };
122 const jsonSchemaStr = yield* encodeJsonForOperation(
123 operation,
124 toJsonSchemaObject(outputSchemaJson),
125 "Failed to encode structured output schema.",
126 );
127 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
128 const descriptors = getProviderOptionDescriptors({
129 caps,
130 selections: resolvedModelSelection.options,
131 });
132 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
133 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
134 const resolvedEffort = resolveClaudeCatalogEffort(
135 catalog,
136 resolvedModelSelection.model,
137 rawEffortSelection,
138 );
139 const cliEffort = normalizeClaudeCatalogEffort(
140 catalog,
141 resolvedEffort,
142 resolvedModelSelection.model,
143 );
144 const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort);
145 const thinkingDescriptor = findDescriptor("thinking");
146 const fastModeDescriptor = findDescriptor("fastMode");
147 const thinking =
148 thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
149 const fastMode =
150 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
151 const settings = {
152 disableAllHooks: true,
153 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
154 ...(fastMode ? { fastMode: true } : {}),
155 ...(ultracode ? { ultracode: true } : {}),
156 };
157 const settingsJson = yield* encodeJsonForOperation(
158 operation,
159 settings,
160 "Failed to encode Claude CLI settings.",
161 );
162​
163 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
164 // Titles need only the supplied prompt, not configuration from the checkout.
165 const workingDirectory =
166 operation === "generateThreadTitle"
167 ? yield* fileSystem
168 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
169 .pipe(
170 Effect.mapError((cause) =>
171 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
172 ),
173 )
174 : cwd;
175 const spawnCommand = yield* resolveSpawnCommand(
176 claudeSettings.binaryPath || "claude",
177 [
178 "-p",
179 "--output-format",
180 "json",
181 "--json-schema",
182 jsonSchemaStr,
183 "--model",
184 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
185 ...(cliEffort ? ["--effort", cliEffort] : []),
186 "--settings",
187 settingsJson,
188 // Metadata prompts need no executable capabilities, even when they contain a skill name.
189 "--tools",
190 "",
191 "--disable-slash-commands",
192 "--strict-mcp-config",
193 "--permission-mode",
194 "dontAsk",
195 ],
196 { env: claudeEnvironment },
197 );
198 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
199 env: claudeEnvironment,
200 cwd: workingDirectory,
201 shell: spawnCommand.shell,
202 stdin: {
203 stream: Stream.encodeText(Stream.make(prompt)),
204 },
205 });
206​
207 const child = yield* commandSpawner
208 .spawn(command)
209 .pipe(
210 Effect.mapError((cause) =>
211 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
212 ),
213 );
214​
215 const [stdout, stderr, exitCode] = yield* Effect.all(
216 [
217 readStreamAsString(operation, child.stdout),
218 readStreamAsString(operation, child.stderr),
219 child.exitCode.pipe(
220 Effect.mapError((cause) =>
221 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
222 ),
223 ),
224 ],
225 { concurrency: "unbounded" },
226 );
227​
228 if (exitCode !== 0) {
229 const stderrDetail = stderr.trim();
230 const stdoutDetail = stdout.trim();
231 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
232 return yield* new TextGenerationError({
233 operation,
234 detail:
235 detail.length > 0
236 ? `Claude CLI command failed: ${detail}`
237 : `Claude CLI command failed with code ${exitCode}.`,
238 });
239 }
240​
241 return stdout;
242 });
243​
244 const rawStdout = yield* runClaudeCommand().pipe(
245 Effect.scoped,
246 Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
247 Effect.flatMap(
248 Option.match({
249 onNone: () =>
250 Effect.fail(
251 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
252 ),
253 onSome: (value) => Effect.succeed(value),
254 }),
255 ),
256 );
257​
258 const output = yield* decodeClaudeOutput(rawStdout).pipe(
259 Effect.catchTags({
260 SchemaError: (cause) =>
261 Effect.fail(
262 new TextGenerationError({
263 operation,
264 detail: "Claude CLI returned unexpected output format.",
265 cause,
266 }),
267 ),
268 }),
269 );
270 const envelope = isClaudeOutputEnvelope(output)
271 ? output
272 : output.findLast((message) => message.type === "result");
273​
274 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
275 return yield* decodeOutput(envelope?.structured_output).pipe(
276 Effect.catchTags({
277 SchemaError: (cause) =>
278 Effect.fail(
279 new TextGenerationError({
280 operation,
281 detail: "Claude returned invalid structured output.",
282 cause,
283 }),
284 ),
285 }),
286 );
287 });
288​
289 return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
290});