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