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

ClaudeTextGeneration.ts

499 lines18.6 KB

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