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

ClaudeTextGeneration.ts

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