Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7import * as Stream from "effect/Stream";
8import { ChildProcess, ChildProcessSpawner } from "effect/process";
9
10import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts";
11import { resolveSpawnCommand } from "@t3tools/shared/shell";
12
13import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
14import {
15 normalizeCliError,
16 toJsonSchemaObject,
17} from "@t3tools/provider-core/server/textGenerationUtils";
18import {
19 getModelSelectionBooleanOptionValue,
20 getModelSelectionStringOptionValue,
21 getProviderOptionDescriptors,
22} from "@t3tools/shared/model";
23import {
24 BUNDLED_CLAUDE_MODEL_CATALOG,
25 type ClaudeModelCatalog,
26 getClaudeCatalogModelCapabilities,
27 normalizeClaudeCatalogEffort,
28 resolveClaudeCatalogApiModelId,
29 resolveClaudeCatalogEffort,
30 resolveClaudeModelSlug,
31 scopeClaudeModelCatalog,
32} from "../provider/ClaudeModelCatalog.ts";
33import {
34 hasClaudeManagedMcpConfig,
35 makeClaudeEnvironment,
36} from "../provider/Drivers/ClaudeHome.ts";
37import { readClaudeLaunchArgSettings } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
38import { resolveAttachmentPath } from "../attachmentStore.ts";
39import * as ServerConfig from "../config.ts";
40
41const CLAUDE_TIMEOUT_MS = 180_000;
42/** `--tools` takes bare names; patterns go in the allow list. */
43const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash";
44/** In dontAsk mode every call outside this list, Bash included, is refused. */
45const CLAUDE_INVESTIGATION_ALLOWED = [
46 "Read",
47 "Grep",
48 "Glob",
49 "Bash(git diff:*)",
50 "Bash(git log:*)",
51 "Bash(git show:*)",
52].join(",");
53// Denies override allows; block git --output/-o because allowed trailing args can otherwise write anywhere.
54const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(",");
55
56const NO_SESSION_PERSISTENCE = "--no-session-persistence";
57// Claude Code before 2.0.63 exits with this on stderr; those runs retry without the flag.
58const NO_SESSION_PERSISTENCE_REJECTED = `error: unknown option '${NO_SESSION_PERSISTENCE}'`;
59// Only a rejection of images as such marks a model text-only, not a size or count limit.
60const IMAGES_UNSUPPORTED =
61 /image[^\n]*(?:not support|unsupported)|(?:not support|unsupported)[^\n]*image/i;
62
63const ClaudeOutputEnvelope = Schema.Struct({
64 structured_output: Schema.Unknown,
65});
66const ClaudeOutputMessage = Schema.Struct({
67 type: Schema.String,
68 structured_output: Schema.optionalKey(Schema.Unknown),
69});
70const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
71
72const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
73const decodeClaudeOutput = Schema.decodeEffect(
74 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
75);
76
77// Only `success` results carry `result`; error subtypes such as
78// error_max_structured_output_retries report through `errors` instead.
79const ClaudeErrorResult = Schema.Struct({
80 is_error: Schema.Literal(true),
81 result: Schema.optionalKey(Schema.String),
82 errors: Schema.optionalKey(Schema.Array(Schema.String)),
83});
84const isClaudeErrorResult = Schema.is(ClaudeErrorResult);
85const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
86
87// Claude reports JSON errors on stdout; stderr may contain only wrapper notices.
88function claudeErrorResult(stdout: string): string | undefined {
89 const output = Option.getOrUndefined(decodeJsonOption(stdout));
90 const messages: ReadonlyArray<unknown> = Array.isArray(output) ? output : [output];
91 return messages
92 .filter(isClaudeErrorResult)
93 .map((message) =>
94 (
95 message.result ??
96 // error_during_execution mixes CLI telemetry into the list.
97 message.errors?.filter((error) => !error.startsWith("[ede_diagnostic]")).join("\n") ??
98 ""
99 ).trim(),
100 )
101 .findLast((result) => result.length > 0);
102}
103
104export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
105 claudeSettings: ClaudeSettings,
106 environment?: NodeJS.ProcessEnv,
107 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
108 routeModelCatalog: (
109 catalog: ClaudeModelCatalog,
110 cwd: string,
111 ) => Effect.Effect<ClaudeModelCatalog> = Effect.succeed,
112) {
113 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
114 const fileSystem = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116 const serverConfig = yield* ServerConfig.ServerConfig;
117 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
118 const scopedModelCatalog = modelCatalog.pipe(
119 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
120 );
121 // Models that failed with images and then succeeded without them; later runs skip the image attempt.
122 const textOnlyModels = new Set<string>();
123
124 const readStreamAsString = <E>(
125 operation: string,
126 stream: Stream.Stream<Uint8Array, E>,
127 ): Effect.Effect<string, TextGenerationError> =>
128 stream.pipe(
129 Stream.decodeText(),
130 Stream.runFold(
131 () => "",
132 (acc, chunk) => acc + chunk,
133 ),
134 Effect.mapError((cause) =>
135 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
136 ),
137 );
138
139 const encodeJsonForOperation = (
140 operation: TextGenerationOperations.Operation,
141 value: unknown,
142 detail: string,
143 ): Effect.Effect<string, TextGenerationError> =>
144 encodeJsonString(value).pipe(
145 Effect.mapError(
146 (cause) =>
147 new TextGenerationError({
148 operation,
149 detail,
150 cause,
151 }),
152 ),
153 );
154
155 const readImageBlocks = Effect.fn("readImageBlocks")(function* (
156 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
157 ) {
158 const blocks: Array<{
159 type: "image";
160 source: { type: "base64"; media_type: string; data: string };
161 }> = [];
162 for (const attachment of attachments ?? []) {
163 if (attachment.type !== "image") continue;
164 const attachmentPath = resolveAttachmentPath({
165 attachmentsDir: serverConfig.attachmentsDir,
166 attachment,
167 });
168 if (!attachmentPath) continue;
169 const bytes = yield* fileSystem
170 .readFile(attachmentPath)
171 .pipe(Effect.orElseSucceed(() => null));
172 if (!bytes) continue;
173 blocks.push({
174 type: "image",
175 source: {
176 type: "base64",
177 media_type: attachment.mimeType,
178 data: Buffer.from(bytes).toString("base64"),
179 },
180 });
181 }
182 return blocks;
183 });
184
185 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
186 operation,
187 cwd,
188 prompt,
189 outputSchema: outputSchemaJson,
190 modelSelection,
191 investigate,
192 attachments,
193 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
194 S["Type"],
195 TextGenerationError,
196 S["DecodingServices"] | Scope.Scope
197 > {
198 const workingDirectory =
199 operation === "generateThreadTitle"
200 ? yield* fileSystem
201 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
202 .pipe(
203 Effect.mapError((cause) =>
204 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
205 ),
206 )
207 : cwd;
208 const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, workingDirectory);
209 const resolvedModelSelection = {
210 ...modelSelection,
211 model: resolveClaudeModelSlug(catalog, modelSelection.model),
212 };
213 const jsonSchemaStr = yield* encodeJsonForOperation(
214 operation,
215 toJsonSchemaObject(outputSchemaJson),
216 "Failed to encode structured output schema.",
217 );
218 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
219 const descriptors = getProviderOptionDescriptors({
220 caps,
221 selections: resolvedModelSelection.options,
222 });
223 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
224 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
225 const resolvedEffort = resolveClaudeCatalogEffort(
226 catalog,
227 resolvedModelSelection.model,
228 rawEffortSelection,
229 );
230 const cliEffort = normalizeClaudeCatalogEffort(
231 catalog,
232 resolvedEffort,
233 resolvedModelSelection.model,
234 );
235 const ultracode = findDescriptor("ultracode")?.currentValue;
236 const thinkingDescriptor = findDescriptor("thinking");
237 const fastModeDescriptor = findDescriptor("fastMode");
238 // Only a chosen value; otherwise Claude Code's own default applies, as in chat turns.
239 const thinking =
240 thinkingDescriptor?.type === "boolean"
241 ? getModelSelectionBooleanOptionValue(resolvedModelSelection, "thinking")
242 : undefined;
243 const fastMode =
244 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
245 const launchArgSettings = yield* readClaudeLaunchArgSettings({
246 settings: claudeSettings,
247 cwd,
248 fileSystem,
249 path,
250 }).pipe(
251 Effect.mapError(
252 (cause) => new TextGenerationError({ operation, detail: cause.message, cause }),
253 ),
254 );
255 const settings = {
256 ...launchArgSettings,
257 disableAllHooks: true,
258 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
259 ...(fastMode ? { fastMode: true } : {}),
260 ...(typeof ultracode === "boolean" ? { ultracode } : {}),
261 };
262 const settingsJson = yield* encodeJsonForOperation(
263 operation,
264 settings,
265 "Failed to encode Claude CLI settings.",
266 );
267
268 // `claude -p` accepts images only as content blocks of a stream-json user message.
269 const apiModelId = resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection);
270 const imageBlocks = textOnlyModels.has(apiModelId) ? [] : yield* readImageBlocks(attachments);
271 const imageStdin =
272 imageBlocks.length > 0
273 ? `${yield* encodeJsonForOperation(
274 operation,
275 {
276 type: "user",
277 message: { role: "user", content: [{ type: "text", text: prompt }, ...imageBlocks] },
278 },
279 "Failed to encode Claude CLI input.",
280 )}\n`
281 : undefined;
282
283 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* (
284 noSessionPersistence: boolean,
285 withImages: boolean,
286 ) {
287 const streamJson = withImages && imageStdin !== undefined;
288 const stdin = streamJson ? imageStdin : prompt;
289 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
290 const spawnCommand = yield* resolveSpawnCommand(
291 claudeSettings.binaryPath || "claude",
292 [
293 "-p",
294 ...(streamJson
295 ? ["--input-format", "stream-json", "--output-format", "stream-json", "--verbose"]
296 : ["--output-format", "json"]),
297 "--json-schema",
298 jsonSchemaStr,
299 "--model",
300 apiModelId,
301 ...(cliEffort ? ["--effort", cliEffort] : []),
302 "--settings",
303 settingsJson,
304 ...(investigate
305 ? [
306 "--tools",
307 CLAUDE_INVESTIGATION_TOOLS,
308 "--allowedTools",
309 CLAUDE_INVESTIGATION_ALLOWED,
310 "--disallowedTools",
311 CLAUDE_INVESTIGATION_DENIED,
312 ]
313 : ["--tools", ""]),
314 ...(investigate ? ["--setting-sources", "user"] : []),
315 "--disable-slash-commands",
316 ...(noSessionPersistence ? [NO_SESSION_PERSISTENCE] : []),
317 // managed-mcp.json already isolates servers and makes Claude reject this flag.
318 ...(managedMcpConfig ? [] : ["--strict-mcp-config"]),
319 "--permission-mode",
320 "dontAsk",
321 ],
322 { env: claudeEnvironment },
323 );
324 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
325 env: claudeEnvironment,
326 cwd: workingDirectory,
327 shell: spawnCommand.shell,
328 stdin: {
329 stream: Stream.encodeText(Stream.make(stdin)),
330 },
331 forceKillAfter: "1 second",
332 });
333
334 const child = yield* commandSpawner
335 .spawn(command)
336 .pipe(
337 Effect.mapError((cause) =>
338 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
339 ),
340 );
341
342 const [stdout, stderr, exitCode] = yield* Effect.all(
343 [
344 readStreamAsString(operation, child.stdout),
345 readStreamAsString(operation, child.stderr),
346 child.exitCode.pipe(
347 Effect.mapError((cause) =>
348 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
349 ),
350 ),
351 ],
352 { concurrency: "unbounded" },
353 );
354
355 // stream-json prints one message per line and ends with the result message.
356 return {
357 stdout: streamJson ? (stdout.trim().split("\n").at(-1) ?? "") : stdout,
358 stderr,
359 exitCode,
360 };
361 });
362
363 const runClaudeAttempt = (withImages: boolean) =>
364 runClaudeCommand(true, withImages).pipe(
365 Effect.filterOrElse(
366 (result) =>
367 result.exitCode === 0 || !result.stderr.includes(NO_SESSION_PERSISTENCE_REJECTED),
368 () => runClaudeCommand(false, withImages),
369 ),
370 );
371
372 const rawStdout = yield* runClaudeAttempt(true).pipe(
373 // Text-only models (custom models behind Anthropic-compatible endpoints) reject image blocks.
374 Effect.filterOrElse(
375 (result) => result.exitCode === 0 || imageStdin === undefined,
376 (imageResult) =>
377 runClaudeAttempt(false).pipe(
378 Effect.tap((result) =>
379 Effect.sync(() => {
380 const imageFailure = `${imageResult.stdout}\n${imageResult.stderr}`;
381 if (result.exitCode === 0 && IMAGES_UNSUPPORTED.test(imageFailure)) {
382 textOnlyModels.add(apiModelId);
383 }
384 }),
385 ),
386 ),
387 ),
388 Effect.flatMap(({ stdout, stderr, exitCode }) => {
389 if (exitCode === 0) return Effect.succeed(stdout);
390 const stderrDetail = stderr.trim();
391 const stdoutDetail = stdout.trim();
392 const detail =
393 claudeErrorResult(stdoutDetail) ??
394 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
395 return Effect.fail(
396 new TextGenerationError({
397 operation,
398 detail:
399 detail.length > 0
400 ? `Claude CLI command failed: ${detail}`
401 : `Claude CLI command failed with code ${exitCode}.`,
402 }),
403 );
404 }),
405 Effect.scoped,
406 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
407 Effect.flatMap(
408 Option.match({
409 onNone: () =>
410 Effect.fail(
411 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
412 ),
413 onSome: (value) => Effect.succeed(value),
414 }),
415 ),
416 );
417
418 const output = yield* decodeClaudeOutput(rawStdout).pipe(
419 Effect.catchTags({
420 SchemaError: (cause) =>
421 Effect.fail(
422 new TextGenerationError({
423 operation,
424 detail: "Claude CLI returned unexpected output format.",
425 cause,
426 }),
427 ),
428 }),
429 );
430 const envelope = isClaudeOutputEnvelope(output)
431 ? output
432 : output.findLast((message) => message.type === "result");
433
434 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
435 return yield* decodeOutput(envelope?.structured_output).pipe(
436 Effect.catchTags({
437 SchemaError: (cause) =>
438 Effect.fail(
439 new TextGenerationError({
440 operation,
441 detail: "Claude returned invalid structured output.",
442 cause,
443 }),
444 ),
445 }),
446 );
447 });
448
449 return TextGenerationOperations.fromRunner(
450 "ClaudeTextGeneration",
451 <S extends Schema.Top>(request: TextGenerationOperations.Request<S>) =>
452 Effect.scoped(runClaudeJson(request)),
453 );
454});