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