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/** The tools an investigation can see. `--tools` takes bare names; patterns go in the allow list. */
44const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash";
45/** What it may run without asking. In dontAsk mode every other call, Bash included, is refused. */
46const CLAUDE_INVESTIGATION_ALLOWED = [
47 "Read",
48 "Grep",
49 "Glob",
50 "Bash(git diff:*)",
51 "Bash(git log:*)",
52 "Bash(git show:*)",
53].join(",");
54/**
55 * The allowed git commands accept any trailing arguments, and `--output` makes each of them write
56 * a file anywhere. Deny rules win over allow rules, so this keeps the investigation read-only.
57 */
58const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(",");
59
60/**
61 * Schema for the wrapper JSON returned by `claude -p --output-format json`.
62 * Verbose mode wraps the result in an array of conversation messages.
63 */
64const ClaudeOutputEnvelope = Schema.Struct({
65 structured_output: Schema.Unknown,
66});
67const ClaudeOutputMessage = Schema.Struct({
68 type: Schema.String,
69 structured_output: Schema.optionalKey(Schema.Unknown),
70});
71const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
72
73const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
74const decodeClaudeOutput = Schema.decodeEffect(
75 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
76);
77
78const ClaudeErrorResult = Schema.Struct({ is_error: Schema.Literal(true), result: Schema.String });
79const isClaudeErrorResult = Schema.is(ClaudeErrorResult);
80const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
81
82/**
83 * The error a failed `claude -p --output-format json` run reports on stdout. Stderr may only
84 * hold notices from a wrapper around the binary, so the caller prefers this when present.
85 */
86function claudeErrorResult(stdout: string): string | undefined {
87 const output = Option.getOrUndefined(decodeJsonOption(stdout));
88 const messages: ReadonlyArray<unknown> = Array.isArray(output) ? output : [output];
89 return messages
90 .filter(isClaudeErrorResult)
91 .map((message) => message.result.trim())
92 .findLast((result) => result.length > 0);
93}
94
95export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
96 claudeSettings: ClaudeSettings,
97 environment?: NodeJS.ProcessEnv,
98 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
99) {
100 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
101 const fileSystem = yield* FileSystem.FileSystem;
102 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
103 const scopedModelCatalog = modelCatalog.pipe(
104 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
105 );
106
107 const readStreamAsString = <E>(
108 operation: string,
109 stream: Stream.Stream<Uint8Array, E>,
110 ): Effect.Effect<string, TextGenerationError> =>
111 stream.pipe(
112 Stream.decodeText(),
113 Stream.runFold(
114 () => "",
115 (acc, chunk) => acc + chunk,
116 ),
117 Effect.mapError((cause) =>
118 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
119 ),
120 );
121
122 const encodeJsonForOperation = (
123 operation: TextGenerationOperations.Operation,
124 value: unknown,
125 detail: string,
126 ): Effect.Effect<string, TextGenerationError> =>
127 encodeJsonString(value).pipe(
128 Effect.mapError(
129 (cause) =>
130 new TextGenerationError({
131 operation,
132 detail,
133 cause,
134 }),
135 ),
136 );
137
138 /**
139 * Spawn the Claude CLI with structured JSON output and return the parsed,
140 * schema-validated result.
141 */
142 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
143 operation,
144 cwd,
145 prompt,
146 outputSchema: outputSchemaJson,
147 modelSelection,
148 investigate,
149 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
150 S["Type"],
151 TextGenerationError,
152 S["DecodingServices"]
153 > {
154 const catalog = yield* scopedModelCatalog;
155 const resolvedModelSelection = {
156 ...modelSelection,
157 model: resolveClaudeModelSlug(catalog, modelSelection.model),
158 };
159 const jsonSchemaStr = yield* encodeJsonForOperation(
160 operation,
161 toJsonSchemaObject(outputSchemaJson),
162 "Failed to encode structured output schema.",
163 );
164 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
165 const descriptors = getProviderOptionDescriptors({
166 caps,
167 selections: resolvedModelSelection.options,
168 });
169 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
170 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
171 const resolvedEffort = resolveClaudeCatalogEffort(
172 catalog,
173 resolvedModelSelection.model,
174 rawEffortSelection,
175 );
176 const cliEffort = normalizeClaudeCatalogEffort(
177 catalog,
178 resolvedEffort,
179 resolvedModelSelection.model,
180 );
181 const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort);
182 const thinkingDescriptor = findDescriptor("thinking");
183 const fastModeDescriptor = findDescriptor("fastMode");
184 const thinking =
185 thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
186 const fastMode =
187 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
188 const settings = {
189 disableAllHooks: true,
190 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
191 ...(fastMode ? { fastMode: true } : {}),
192 ...(ultracode ? { ultracode: true } : {}),
193 };
194 const settingsJson = yield* encodeJsonForOperation(
195 operation,
196 settings,
197 "Failed to encode Claude CLI settings.",
198 );
199
200 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
201 // Titles need only the supplied prompt, not configuration from the checkout.
202 const workingDirectory =
203 operation === "generateThreadTitle"
204 ? yield* fileSystem
205 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
206 .pipe(
207 Effect.mapError((cause) =>
208 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
209 ),
210 )
211 : cwd;
212 const spawnCommand = yield* resolveSpawnCommand(
213 claudeSettings.binaryPath || "claude",
214 [
215 "-p",
216 "--output-format",
217 "json",
218 "--json-schema",
219 jsonSchemaStr,
220 "--model",
221 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
222 ...(cliEffort ? ["--effort", cliEffort] : []),
223 "--settings",
224 settingsJson,
225 // Metadata prompts need no executable capabilities, even when they contain a skill name.
226 // An investigation gets the read-only file tools and Git's read commands, and nothing
227 // that writes: in dontAsk mode anything not allowed here is refused.
228 ...(investigate
229 ? [
230 "--tools",
231 CLAUDE_INVESTIGATION_TOOLS,
232 "--allowedTools",
233 CLAUDE_INVESTIGATION_ALLOWED,
234 "--disallowedTools",
235 CLAUDE_INVESTIGATION_DENIED,
236 ]
237 : ["--tools", ""]),
238 "--disable-slash-commands",
239 "--strict-mcp-config",
240 "--permission-mode",
241 "dontAsk",
242 ],
243 { env: claudeEnvironment },
244 );
245 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
246 env: claudeEnvironment,
247 cwd: workingDirectory,
248 shell: spawnCommand.shell,
249 stdin: {
250 stream: Stream.encodeText(Stream.make(prompt)),
251 },
252 });
253
254 const child = yield* commandSpawner
255 .spawn(command)
256 .pipe(
257 Effect.mapError((cause) =>
258 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
259 ),
260 );
261
262 const [stdout, stderr, exitCode] = yield* Effect.all(
263 [
264 readStreamAsString(operation, child.stdout),
265 readStreamAsString(operation, child.stderr),
266 child.exitCode.pipe(
267 Effect.mapError((cause) =>
268 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
269 ),
270 ),
271 ],
272 { concurrency: "unbounded" },
273 );
274
275 if (exitCode !== 0) {
276 const stderrDetail = stderr.trim();
277 const stdoutDetail = stdout.trim();
278 const detail =
279 claudeErrorResult(stdoutDetail) ??
280 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
281 return yield* new TextGenerationError({
282 operation,
283 detail:
284 detail.length > 0
285 ? `Claude CLI command failed: ${detail}`
286 : `Claude CLI command failed with code ${exitCode}.`,
287 });
288 }
289
290 return stdout;
291 });
292
293 const rawStdout = yield* runClaudeCommand().pipe(
294 Effect.scoped,
295 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
296 Effect.flatMap(
297 Option.match({
298 onNone: () =>
299 Effect.fail(
300 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
301 ),
302 onSome: (value) => Effect.succeed(value),
303 }),
304 ),
305 );
306
307 const output = yield* decodeClaudeOutput(rawStdout).pipe(
308 Effect.catchTags({
309 SchemaError: (cause) =>
310 Effect.fail(
311 new TextGenerationError({
312 operation,
313 detail: "Claude CLI returned unexpected output format.",
314 cause,
315 }),
316 ),
317 }),
318 );
319 const envelope = isClaudeOutputEnvelope(output)
320 ? output
321 : output.findLast((message) => message.type === "result");
322
323 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
324 return yield* decodeOutput(envelope?.structured_output).pipe(
325 Effect.catchTags({
326 SchemaError: (cause) =>
327 Effect.fail(
328 new TextGenerationError({
329 operation,
330 detail: "Claude returned invalid structured output.",
331 cause,
332 }),
333 ),
334 }),
335 );
336 });
337
338 return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
339});