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
78export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
79 claudeSettings: ClaudeSettings,
80 environment?: NodeJS.ProcessEnv,
81 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
82) {
83 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
84 const fileSystem = yield* FileSystem.FileSystem;
85 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
86 const scopedModelCatalog = modelCatalog.pipe(
87 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
88 );
89
90 const readStreamAsString = <E>(
91 operation: string,
92 stream: Stream.Stream<Uint8Array, E>,
93 ): Effect.Effect<string, TextGenerationError> =>
94 stream.pipe(
95 Stream.decodeText(),
96 Stream.runFold(
97 () => "",
98 (acc, chunk) => acc + chunk,
99 ),
100 Effect.mapError((cause) =>
101 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
102 ),
103 );
104
105 const encodeJsonForOperation = (
106 operation: TextGenerationOperations.Operation,
107 value: unknown,
108 detail: string,
109 ): Effect.Effect<string, TextGenerationError> =>
110 encodeJsonString(value).pipe(
111 Effect.mapError(
112 (cause) =>
113 new TextGenerationError({
114 operation,
115 detail,
116 cause,
117 }),
118 ),
119 );
120
121 /**
122 * Spawn the Claude CLI with structured JSON output and return the parsed,
123 * schema-validated result.
124 */
125 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
126 operation,
127 cwd,
128 prompt,
129 outputSchema: outputSchemaJson,
130 modelSelection,
131 investigate,
132 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
133 S["Type"],
134 TextGenerationError,
135 S["DecodingServices"]
136 > {
137 const catalog = yield* scopedModelCatalog;
138 const resolvedModelSelection = {
139 ...modelSelection,
140 model: resolveClaudeModelSlug(catalog, modelSelection.model),
141 };
142 const jsonSchemaStr = yield* encodeJsonForOperation(
143 operation,
144 toJsonSchemaObject(outputSchemaJson),
145 "Failed to encode structured output schema.",
146 );
147 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
148 const descriptors = getProviderOptionDescriptors({
149 caps,
150 selections: resolvedModelSelection.options,
151 });
152 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
153 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
154 const resolvedEffort = resolveClaudeCatalogEffort(
155 catalog,
156 resolvedModelSelection.model,
157 rawEffortSelection,
158 );
159 const cliEffort = normalizeClaudeCatalogEffort(
160 catalog,
161 resolvedEffort,
162 resolvedModelSelection.model,
163 );
164 const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort);
165 const thinkingDescriptor = findDescriptor("thinking");
166 const fastModeDescriptor = findDescriptor("fastMode");
167 const thinking =
168 thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
169 const fastMode =
170 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
171 const settings = {
172 disableAllHooks: true,
173 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
174 ...(fastMode ? { fastMode: true } : {}),
175 ...(ultracode ? { ultracode: true } : {}),
176 };
177 const settingsJson = yield* encodeJsonForOperation(
178 operation,
179 settings,
180 "Failed to encode Claude CLI settings.",
181 );
182
183 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
184 // Titles need only the supplied prompt, not configuration from the checkout.
185 const workingDirectory =
186 operation === "generateThreadTitle"
187 ? yield* fileSystem
188 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
189 .pipe(
190 Effect.mapError((cause) =>
191 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
192 ),
193 )
194 : cwd;
195 const spawnCommand = yield* resolveSpawnCommand(
196 claudeSettings.binaryPath || "claude",
197 [
198 "-p",
199 "--output-format",
200 "json",
201 "--json-schema",
202 jsonSchemaStr,
203 "--model",
204 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
205 ...(cliEffort ? ["--effort", cliEffort] : []),
206 "--settings",
207 settingsJson,
208 // Metadata prompts need no executable capabilities, even when they contain a skill name.
209 // An investigation gets the read-only file tools and Git's read commands, and nothing
210 // that writes: in dontAsk mode anything not allowed here is refused.
211 ...(investigate
212 ? [
213 "--tools",
214 CLAUDE_INVESTIGATION_TOOLS,
215 "--allowedTools",
216 CLAUDE_INVESTIGATION_ALLOWED,
217 "--disallowedTools",
218 CLAUDE_INVESTIGATION_DENIED,
219 ]
220 : ["--tools", ""]),
221 "--disable-slash-commands",
222 "--strict-mcp-config",
223 "--permission-mode",
224 "dontAsk",
225 ],
226 { env: claudeEnvironment },
227 );
228 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
229 env: claudeEnvironment,
230 cwd: workingDirectory,
231 shell: spawnCommand.shell,
232 stdin: {
233 stream: Stream.encodeText(Stream.make(prompt)),
234 },
235 });
236
237 const child = yield* commandSpawner
238 .spawn(command)
239 .pipe(
240 Effect.mapError((cause) =>
241 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
242 ),
243 );
244
245 const [stdout, stderr, exitCode] = yield* Effect.all(
246 [
247 readStreamAsString(operation, child.stdout),
248 readStreamAsString(operation, child.stderr),
249 child.exitCode.pipe(
250 Effect.mapError((cause) =>
251 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
252 ),
253 ),
254 ],
255 { concurrency: "unbounded" },
256 );
257
258 if (exitCode !== 0) {
259 const stderrDetail = stderr.trim();
260 const stdoutDetail = stdout.trim();
261 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
262 return yield* new TextGenerationError({
263 operation,
264 detail:
265 detail.length > 0
266 ? `Claude CLI command failed: ${detail}`
267 : `Claude CLI command failed with code ${exitCode}.`,
268 });
269 }
270
271 return stdout;
272 });
273
274 const rawStdout = yield* runClaudeCommand().pipe(
275 Effect.scoped,
276 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
277 Effect.flatMap(
278 Option.match({
279 onNone: () =>
280 Effect.fail(
281 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
282 ),
283 onSome: (value) => Effect.succeed(value),
284 }),
285 ),
286 );
287
288 const output = yield* decodeClaudeOutput(rawStdout).pipe(
289 Effect.catchTags({
290 SchemaError: (cause) =>
291 Effect.fail(
292 new TextGenerationError({
293 operation,
294 detail: "Claude CLI returned unexpected output format.",
295 cause,
296 }),
297 ),
298 }),
299 );
300 const envelope = isClaudeOutputEnvelope(output)
301 ? output
302 : output.findLast((message) => message.type === "result");
303
304 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
305 return yield* decodeOutput(envelope?.structured_output).pipe(
306 Effect.catchTags({
307 SchemaError: (cause) =>
308 Effect.fail(
309 new TextGenerationError({
310 operation,
311 detail: "Claude returned invalid structured output.",
312 cause,
313 }),
314 ),
315 }),
316 );
317 });
318
319 return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
320});