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

ClaudeTextGeneration.ts

329 lines11.3 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import { ChildProcess, ChildProcessSpawner } from "effect/process";
7​
8import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts";
9import { resolveSpawnCommand } from "@t3tools/shared/shell";
10​
11import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
12import {
13 normalizeCliError,
14 toJsonSchemaObject,
15} from "@t3tools/provider-core/server/textGenerationUtils";
16import {
17 getModelSelectionBooleanOptionValue,
18 getModelSelectionStringOptionValue,
19 getProviderOptionDescriptors,
20} from "@t3tools/shared/model";
21import {
22 BUNDLED_CLAUDE_MODEL_CATALOG,
23 type ClaudeModelCatalog,
24 getClaudeCatalogModelCapabilities,
25 isClaudeCatalogUltracodeEffort,
26 normalizeClaudeCatalogEffort,
27 resolveClaudeCatalogApiModelId,
28 resolveClaudeCatalogEffort,
29 resolveClaudeModelSlug,
30 scopeClaudeModelCatalog,
31} from "../provider/ClaudeModelCatalog.ts";
32import {
33 hasClaudeManagedMcpConfig,
34 makeClaudeEnvironment,
35} from "../provider/Drivers/ClaudeHome.ts";
36​
37const CLAUDE_TIMEOUT_MS = 180_000;
38/** The tools an investigation can see. `--tools` takes bare names; patterns go in the allow list. */
39const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash";
40/** What it may run without asking. In dontAsk mode every other call, Bash included, is refused. */
41const CLAUDE_INVESTIGATION_ALLOWED = [
42 "Read",
43 "Grep",
44 "Glob",
45 "Bash(git diff:*)",
46 "Bash(git log:*)",
47 "Bash(git show:*)",
48].join(",");
49/**
50 * The allowed git commands accept any trailing arguments, and `--output` makes each of them write
51 * a file anywhere. Deny rules win over allow rules, so this keeps the investigation read-only.
52 */
53const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(",");
54​
55const ClaudeOutputEnvelope = Schema.Struct({
56 structured_output: Schema.Unknown,
57});
58const ClaudeOutputMessage = Schema.Struct({
59 type: Schema.String,
60 structured_output: Schema.optionalKey(Schema.Unknown),
61});
62const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
63​
64const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
65const decodeClaudeOutput = Schema.decodeEffect(
66 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
67);
68​
69const ClaudeErrorResult = Schema.Struct({ is_error: Schema.Literal(true), result: Schema.String });
70const isClaudeErrorResult = Schema.is(ClaudeErrorResult);
71const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
72​
73/**
74 * The error a failed `claude -p --output-format json` run reports on stdout. Stderr may only
75 * hold notices from a wrapper around the binary, so the caller prefers this when present.
76 */
77function claudeErrorResult(stdout: string): string | undefined {
78 const output = Option.getOrUndefined(decodeJsonOption(stdout));
79 const messages: ReadonlyArray<unknown> = Array.isArray(output) ? output : [output];
80 return messages
81 .filter(isClaudeErrorResult)
82 .map((message) => message.result.trim())
83 .findLast((result) => result.length > 0);
85​
86export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
87 claudeSettings: ClaudeSettings,
88 environment?: NodeJS.ProcessEnv,
89 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
90) {
91 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
92 const fileSystem = yield* FileSystem.FileSystem;
93 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
94 const scopedModelCatalog = modelCatalog.pipe(
95 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
96 );
97​
98 const readStreamAsString = <E>(
99 operation: string,
100 stream: Stream.Stream<Uint8Array, E>,
101 ): Effect.Effect<string, TextGenerationError> =>
102 stream.pipe(
103 Stream.decodeText(),
104 Stream.runFold(
105 () => "",
106 (acc, chunk) => acc + chunk,
107 ),
108 Effect.mapError((cause) =>
109 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
110 ),
111 );
112​
113 const encodeJsonForOperation = (
114 operation: TextGenerationOperations.Operation,
115 value: unknown,
116 detail: string,
117 ): Effect.Effect<string, TextGenerationError> =>
118 encodeJsonString(value).pipe(
119 Effect.mapError(
120 (cause) =>
121 new TextGenerationError({
122 operation,
123 detail,
124 cause,
125 }),
126 ),
127 );
128​
129 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
130 operation,
131 cwd,
132 prompt,
133 outputSchema: outputSchemaJson,
134 modelSelection,
135 investigate,
136 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
137 S["Type"],
138 TextGenerationError,
139 S["DecodingServices"]
140 > {
141 const catalog = yield* scopedModelCatalog;
142 const resolvedModelSelection = {
143 ...modelSelection,
144 model: resolveClaudeModelSlug(catalog, modelSelection.model),
145 };
146 const jsonSchemaStr = yield* encodeJsonForOperation(
147 operation,
148 toJsonSchemaObject(outputSchemaJson),
149 "Failed to encode structured output schema.",
150 );
151 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
152 const descriptors = getProviderOptionDescriptors({
153 caps,
154 selections: resolvedModelSelection.options,
155 });
156 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
157 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
158 const resolvedEffort = resolveClaudeCatalogEffort(
159 catalog,
160 resolvedModelSelection.model,
161 rawEffortSelection,
162 );
163 const cliEffort = normalizeClaudeCatalogEffort(
164 catalog,
165 resolvedEffort,
166 resolvedModelSelection.model,
167 );
168 const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort);
169 const thinkingDescriptor = findDescriptor("thinking");
170 const fastModeDescriptor = findDescriptor("fastMode");
171 // Only a chosen value; otherwise Claude Code's own default applies, as in chat turns.
172 const thinking =
173 thinkingDescriptor?.type === "boolean"
174 ? getModelSelectionBooleanOptionValue(resolvedModelSelection, "thinking")
175 : undefined;
176 const fastMode =
177 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
178 const settings = {
179 disableAllHooks: true,
180 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
181 ...(fastMode ? { fastMode: true } : {}),
182 ...(ultracode ? { ultracode: true } : {}),
183 };
184 const settingsJson = yield* encodeJsonForOperation(
185 operation,
186 settings,
187 "Failed to encode Claude CLI settings.",
188 );
189​
190 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
191 const workingDirectory =
192 operation === "generateThreadTitle"
193 ? yield* fileSystem
194 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
195 .pipe(
196 Effect.mapError((cause) =>
197 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
198 ),
199 )
200 : cwd;
201 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
202 const spawnCommand = yield* resolveSpawnCommand(
203 claudeSettings.binaryPath || "claude",
204 [
205 "-p",
206 "--output-format",
207 "json",
208 "--json-schema",
209 jsonSchemaStr,
210 "--model",
211 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
212 ...(cliEffort ? ["--effort", cliEffort] : []),
213 "--settings",
214 settingsJson,
215 ...(investigate
216 ? [
217 "--tools",
218 CLAUDE_INVESTIGATION_TOOLS,
219 "--allowedTools",
220 CLAUDE_INVESTIGATION_ALLOWED,
221 "--disallowedTools",
222 CLAUDE_INVESTIGATION_DENIED,
223 ]
224 : ["--tools", ""]),
225 "--disable-slash-commands",
226 // Claude refuses this flag next to a managed-mcp.json, which already keeps the
227 // user's own MCP servers out.
228 ...(managedMcpConfig ? [] : ["--strict-mcp-config"]),
229 "--permission-mode",
230 "dontAsk",
231 ],
232 { env: claudeEnvironment },
233 );
234 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
235 env: claudeEnvironment,
236 cwd: workingDirectory,
237 shell: spawnCommand.shell,
238 stdin: {
239 stream: Stream.encodeText(Stream.make(prompt)),
240 },
241 forceKillAfter: "1 second",
242 });
243​
244 const child = yield* commandSpawner
245 .spawn(command)
246 .pipe(
247 Effect.mapError((cause) =>
248 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
249 ),
250 );
251​
252 const [stdout, stderr, exitCode] = yield* Effect.all(
253 [
254 readStreamAsString(operation, child.stdout),
255 readStreamAsString(operation, child.stderr),
256 child.exitCode.pipe(
257 Effect.mapError((cause) =>
258 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
259 ),
260 ),
261 ],
262 { concurrency: "unbounded" },
263 );
264​
265 if (exitCode !== 0) {
266 const stderrDetail = stderr.trim();
267 const stdoutDetail = stdout.trim();
268 const detail =
269 claudeErrorResult(stdoutDetail) ??
270 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
271 return yield* new TextGenerationError({
272 operation,
273 detail:
274 detail.length > 0
275 ? `Claude CLI command failed: ${detail}`
276 : `Claude CLI command failed with code ${exitCode}.`,
277 });
278 }
279​
280 return stdout;
281 });
282​
283 const rawStdout = yield* runClaudeCommand().pipe(
284 Effect.scoped,
285 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
286 Effect.flatMap(
287 Option.match({
288 onNone: () =>
289 Effect.fail(
290 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
291 ),
292 onSome: (value) => Effect.succeed(value),
293 }),
294 ),
295 );
296​
297 const output = yield* decodeClaudeOutput(rawStdout).pipe(
298 Effect.catchTags({
299 SchemaError: (cause) =>
300 Effect.fail(
301 new TextGenerationError({
302 operation,
303 detail: "Claude CLI returned unexpected output format.",
304 cause,
305 }),
306 ),
307 }),
308 );
309 const envelope = isClaudeOutputEnvelope(output)
310 ? output
311 : output.findLast((message) => message.type === "result");
312​
313 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
314 return yield* decodeOutput(envelope?.structured_output).pipe(
315 Effect.catchTags({
316 SchemaError: (cause) =>
317 Effect.fail(
318 new TextGenerationError({
319 operation,
320 detail: "Claude returned invalid structured output.",
321 cause,
322 }),
323 ),
324 }),
325 );
326 });
327​
328 return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
329});