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

ClaudeTextGeneration.ts

426 lines14.9 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 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​
60const ClaudeOutputEnvelope = Schema.Struct({
61 structured_output: Schema.Unknown,
62});
63const ClaudeOutputMessage = Schema.Struct({
64 type: Schema.String,
65 structured_output: Schema.optionalKey(Schema.Unknown),
66});
67const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
68​
69const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
70const decodeClaudeOutput = Schema.decodeEffect(
71 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
72);
73​
74// Only `success` results carry `result`; error subtypes such as
75// error_max_structured_output_retries report through `errors` instead.
76const ClaudeErrorResult = Schema.Struct({
77 is_error: Schema.Literal(true),
78 result: Schema.optionalKey(Schema.String),
79 errors: Schema.optionalKey(Schema.Array(Schema.String)),
80});
81const isClaudeErrorResult = Schema.is(ClaudeErrorResult);
82const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
83​
84// Claude reports JSON errors on stdout; stderr may contain only wrapper notices.
85function claudeErrorResult(stdout: string): string | undefined {
86 const output = Option.getOrUndefined(decodeJsonOption(stdout));
87 const messages: ReadonlyArray<unknown> = Array.isArray(output) ? output : [output];
88 return messages
89 .filter(isClaudeErrorResult)
90 .map((message) =>
91 (
92 message.result ??
93 // error_during_execution mixes CLI telemetry into the list.
94 message.errors?.filter((error) => !error.startsWith("[ede_diagnostic]")).join("\n") ??
95 ""
96 ).trim(),
97 )
98 .findLast((result) => result.length > 0);
100​
101export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
102 claudeSettings: ClaudeSettings,
103 environment?: NodeJS.ProcessEnv,
104 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
105 routeModelCatalog: (
106 catalog: ClaudeModelCatalog,
107 cwd: string,
108 ) => Effect.Effect<ClaudeModelCatalog> = Effect.succeed,
109) {
110 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
111 const fileSystem = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const serverConfig = yield* ServerConfig.ServerConfig;
114 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
115 const scopedModelCatalog = modelCatalog.pipe(
116 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
117 );
118​
119 const readStreamAsString = <E>(
120 operation: string,
121 stream: Stream.Stream<Uint8Array, E>,
122 ): Effect.Effect<string, TextGenerationError> =>
123 stream.pipe(
124 Stream.decodeText(),
125 Stream.runFold(
126 () => "",
127 (acc, chunk) => acc + chunk,
128 ),
129 Effect.mapError((cause) =>
130 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
131 ),
132 );
133​
134 const encodeJsonForOperation = (
135 operation: TextGenerationOperations.Operation,
136 value: unknown,
137 detail: string,
138 ): Effect.Effect<string, TextGenerationError> =>
139 encodeJsonString(value).pipe(
140 Effect.mapError(
141 (cause) =>
142 new TextGenerationError({
143 operation,
144 detail,
145 cause,
146 }),
147 ),
148 );
149​
150 const readImageBlocks = Effect.fn("readImageBlocks")(function* (
151 attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
152 ) {
153 const blocks: Array<{
154 type: "image";
155 source: { type: "base64"; media_type: string; data: string };
156 }> = [];
157 for (const attachment of attachments ?? []) {
158 if (attachment.type !== "image") continue;
159 const attachmentPath = resolveAttachmentPath({
160 attachmentsDir: serverConfig.attachmentsDir,
161 attachment,
162 });
163 if (!attachmentPath) continue;
164 const bytes = yield* fileSystem
165 .readFile(attachmentPath)
166 .pipe(Effect.orElseSucceed(() => null));
167 if (!bytes) continue;
168 blocks.push({
169 type: "image",
170 source: {
171 type: "base64",
172 media_type: attachment.mimeType,
173 data: Buffer.from(bytes).toString("base64"),
174 },
175 });
176 }
177 return blocks;
178 });
179​
180 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
181 operation,
182 cwd,
183 prompt,
184 outputSchema: outputSchemaJson,
185 modelSelection,
186 investigate,
187 attachments,
188 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
189 S["Type"],
190 TextGenerationError,
191 S["DecodingServices"] | Scope.Scope
192 > {
193 const workingDirectory =
194 operation === "generateThreadTitle"
195 ? yield* fileSystem
196 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
197 .pipe(
198 Effect.mapError((cause) =>
199 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
200 ),
201 )
202 : cwd;
203 const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, workingDirectory);
204 const resolvedModelSelection = {
205 ...modelSelection,
206 model: resolveClaudeModelSlug(catalog, modelSelection.model),
207 };
208 const jsonSchemaStr = yield* encodeJsonForOperation(
209 operation,
210 toJsonSchemaObject(outputSchemaJson),
211 "Failed to encode structured output schema.",
212 );
213 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
214 const descriptors = getProviderOptionDescriptors({
215 caps,
216 selections: resolvedModelSelection.options,
217 });
218 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
219 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
220 const resolvedEffort = resolveClaudeCatalogEffort(
221 catalog,
222 resolvedModelSelection.model,
223 rawEffortSelection,
224 );
225 const cliEffort = normalizeClaudeCatalogEffort(
226 catalog,
227 resolvedEffort,
228 resolvedModelSelection.model,
229 );
230 const ultracode = findDescriptor("ultracode")?.currentValue;
231 const thinkingDescriptor = findDescriptor("thinking");
232 const fastModeDescriptor = findDescriptor("fastMode");
233 // Only a chosen value; otherwise Claude Code's own default applies, as in chat turns.
234 const thinking =
235 thinkingDescriptor?.type === "boolean"
236 ? getModelSelectionBooleanOptionValue(resolvedModelSelection, "thinking")
237 : undefined;
238 const fastMode =
239 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
240 const launchArgSettings = yield* readClaudeLaunchArgSettings({
241 settings: claudeSettings,
242 cwd,
243 fileSystem,
244 path,
245 }).pipe(
246 Effect.mapError(
247 (cause) => new TextGenerationError({ operation, detail: cause.message, cause }),
248 ),
249 );
250 const settings = {
251 ...launchArgSettings,
252 disableAllHooks: true,
253 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
254 ...(fastMode ? { fastMode: true } : {}),
255 ...(typeof ultracode === "boolean" ? { ultracode } : {}),
256 };
257 const settingsJson = yield* encodeJsonForOperation(
258 operation,
259 settings,
260 "Failed to encode Claude CLI settings.",
261 );
262​
263 // `claude -p` accepts images only as content blocks of a stream-json user message.
264 const imageBlocks = yield* readImageBlocks(attachments);
265 const streamJson = imageBlocks.length > 0;
266 const stdin = streamJson
267 ? `${yield* encodeJsonForOperation(
268 operation,
269 {
270 type: "user",
271 message: { role: "user", content: [{ type: "text", text: prompt }, ...imageBlocks] },
272 },
273 "Failed to encode Claude CLI input.",
274 )}\n`
275 : prompt;
276​
277 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* (
278 noSessionPersistence: boolean,
279 ) {
280 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
281 const spawnCommand = yield* resolveSpawnCommand(
282 claudeSettings.binaryPath || "claude",
283 [
284 "-p",
285 ...(streamJson
286 ? ["--input-format", "stream-json", "--output-format", "stream-json", "--verbose"]
287 : ["--output-format", "json"]),
288 "--json-schema",
289 jsonSchemaStr,
290 "--model",
291 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
292 ...(cliEffort ? ["--effort", cliEffort] : []),
293 "--settings",
294 settingsJson,
295 ...(investigate
296 ? [
297 "--tools",
298 CLAUDE_INVESTIGATION_TOOLS,
299 "--allowedTools",
300 CLAUDE_INVESTIGATION_ALLOWED,
301 "--disallowedTools",
302 CLAUDE_INVESTIGATION_DENIED,
303 ]
304 : ["--tools", ""]),
305 ...(investigate ? ["--setting-sources", "user"] : []),
306 "--disable-slash-commands",
307 ...(noSessionPersistence ? [NO_SESSION_PERSISTENCE] : []),
308 // managed-mcp.json already isolates servers and makes Claude reject this flag.
309 ...(managedMcpConfig ? [] : ["--strict-mcp-config"]),
310 "--permission-mode",
311 "dontAsk",
312 ],
313 { env: claudeEnvironment },
314 );
315 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
316 env: claudeEnvironment,
317 cwd: workingDirectory,
318 shell: spawnCommand.shell,
319 stdin: {
320 stream: Stream.encodeText(Stream.make(stdin)),
321 },
322 forceKillAfter: "1 second",
323 });
324​
325 const child = yield* commandSpawner
326 .spawn(command)
327 .pipe(
328 Effect.mapError((cause) =>
329 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
330 ),
331 );
332​
333 const [stdout, stderr, exitCode] = yield* Effect.all(
334 [
335 readStreamAsString(operation, child.stdout),
336 readStreamAsString(operation, child.stderr),
337 child.exitCode.pipe(
338 Effect.mapError((cause) =>
339 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
340 ),
341 ),
342 ],
343 { concurrency: "unbounded" },
344 );
345​
346 // stream-json prints one message per line and ends with the result message.
347 return {
348 stdout: streamJson ? (stdout.trim().split("\n").at(-1) ?? "") : stdout,
349 stderr,
350 exitCode,
351 };
352 });
353​
354 const rawStdout = yield* runClaudeCommand(true).pipe(
355 Effect.filterOrElse(
356 (result) =>
357 result.exitCode === 0 || !result.stderr.includes(NO_SESSION_PERSISTENCE_REJECTED),
358 () => runClaudeCommand(false),
359 ),
360 Effect.flatMap(({ stdout, stderr, exitCode }) => {
361 if (exitCode === 0) return Effect.succeed(stdout);
362 const stderrDetail = stderr.trim();
363 const stdoutDetail = stdout.trim();
364 const detail =
365 claudeErrorResult(stdoutDetail) ??
366 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
367 return Effect.fail(
368 new TextGenerationError({
369 operation,
370 detail:
371 detail.length > 0
372 ? `Claude CLI command failed: ${detail}`
373 : `Claude CLI command failed with code ${exitCode}.`,
374 }),
375 );
376 }),
377 Effect.scoped,
378 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
379 Effect.flatMap(
380 Option.match({
381 onNone: () =>
382 Effect.fail(
383 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
384 ),
385 onSome: (value) => Effect.succeed(value),
386 }),
387 ),
388 );
389​
390 const output = yield* decodeClaudeOutput(rawStdout).pipe(
391 Effect.catchTags({
392 SchemaError: (cause) =>
393 Effect.fail(
394 new TextGenerationError({
395 operation,
396 detail: "Claude CLI returned unexpected output format.",
397 cause,
398 }),
399 ),
400 }),
401 );
402 const envelope = isClaudeOutputEnvelope(output)
403 ? output
404 : output.findLast((message) => message.type === "result");
405​
406 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
407 return yield* decodeOutput(envelope?.structured_output).pipe(
408 Effect.catchTags({
409 SchemaError: (cause) =>
410 Effect.fail(
411 new TextGenerationError({
412 operation,
413 detail: "Claude returned invalid structured output.",
414 cause,
415 }),
416 ),
417 }),
418 );
419 });
420​
421 return TextGenerationOperations.fromRunner(
422 "ClaudeTextGeneration",
423 <S extends Schema.Top>(request: TextGenerationOperations.Request<S>) =>
424 Effect.scoped(runClaudeJson(request)),
425 );
426});